原创Blog,转载请注明出处
http://blog.csdn.net/hello_hwc
本文主要补充上一篇文章中未提及的协议的功能
一、扩展中的协议
1、通过扩展来遵循协议protocol TextProtocol { func asString() -> String } class ID{ var ID:Int = 0 } extension ID:TextProtocol{ func asString()->String{ return String(ID) } }2、通过扩展补充协议声明
class ID{ var ID:Int = 0 func asString()->String{ return String(ID) } } extension ID:TextProtocol
protocol HwcProtocol{ func logDescription() } class Obj1:HwcProtocol{ func logDescription(){ println("From obj1") } } class Obj2:HwcProtocol{ func logDescription(){ println("From obj2") } } class Obj3:HwcProtocol{ func logDescription(){ println("From obj3") } } var obj1 = Obj1() var obj2 = Obj2() var obj3 = Obj3() let things: [HwcProtocol] = [obj1,obj2,obj3] for thing in things { println(thing.logDescription()) }
protocol InheritingProtocol: SomeProtocol, AnotherProtocol { // 协议定义 }
protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol { // class-only protocol definition goes here }
protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person: Named, Aged { var name: String var age: Int } //这里protocol<Named, Aged>表示同时遵循两个协议的类型 func wishHappyBirthday(celebrator: protocol<Named, Aged>) { println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!") } let birthdayPerson = Person(name: "Malcolm", age: 21) wishHappyBirthday(birthdayPerson) // 输出 "Happy birthday Malcolm - you're 21
@objc protocol CounterDataSource { optional func incrementForCount(count: Int) -> Int optional var fixedIncrement: Int { get } } @objc class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count) { count += amount } else if let amount = dataSource?.fixedIncrement? { count += amount } init(count:Int){ self.count = count } } }声明一个计数器协议,然后功能类Counter完成技术,Counter有一个属性count用来返回当前的计数。
class HwcTest:CounterDataSource{ var counter:Counter init(counter:Counter){ self.counter = counter; self.counter.dataSource = self; } var fixedIncrement = 10 func hwcPrint(){ for i in 1...10{ println(counter.count) counter.increment() } } }同样,也可以使用
class HwcTest:CounterDataSource{ var counter:Counter init(counter:Counter){ self.counter = counter; self.counter.dataSource = self; } func incrementForCount(count: Int)->Int{ return count+1 } func hwcPrint(){ for i in 1...10{ println(counter.count) counter.increment() } } }