swift的语法小demo4(协议protocol)
// // main.swift // SwiftGrammarStudy // // Created by dongway on 14-6-6. // Copyright (c) 2014年 dongway. All rights reserved. // import Foundation 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 /* 结构体,方法实现需要加mutating标记(上面的class类不需要) */ struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription /* 这个我也不明白怎么回事 扩展用于在已有的类型上增加新的功能(比如新的方法或属性) */ extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } let protocolValue: ExampleProtocol = a println("\(protocolValue.simpleDescription)")