您的位置:首页 > 移动开发 > Swift

Swift 协议(protocol)和扩展(extension)

2014-06-04 11:29 330 查看
协议

  Swift 使用
protocol
定义协议:

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


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

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


扩展

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

extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust () {
self += 42
}
}
7.simpleDescription
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: