码迷,mamicode.com
首页 > 编程语言 > 详细

Swift学习5---协议(protocol)和扩展(extension)

时间:2015-05-14 00:50:02      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

1.协议

  Swift使用protocol定义协议:

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

  类型、枚举和结构都可以实现协议:

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += " Now 100% adjusted."
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

2.扩展

  扩展用于在已有的类型上增加新的功能(比如新的方法或属性),Swift使用extension声明扩展:

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
7.simpleDescription

 

Swift学习5---协议(protocol)和扩展(extension)

标签:

原文地址:http://www.cnblogs.com/ShawnLi/p/4502184.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!