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

时间:2015-05-14 00:50:02   收藏:0   阅读:170

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

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!