标签:
协议不同于继承、扩展。继承是需要对子类继承或复写。扩展是对系统给的类进行扩展,而协议是写好一个东西,各个方法和结构体都去实现它的方法和属性。
1.协议-属性
protocol SomeProtocol{ var mustBeSettable:Int {set get} var doesNotNeedToBrStttabe:Int {get} //支读 static var someTypeProperty:Int {get set} //静态属性 } protocol FullyNamed{ var fullName:String {get} } struct Person:FullyNamed { var fullName:String } let john = Person(fullName: "John Appleseed")
2.协议-方法
protocol RandomNumberGenerator{ func random() -> Double } class Linear:RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom*a+c)%m) return lastRandom/m } } let generator = Linear() print("\(generator.random())")
3.将协议当作类型使用
把协议当做类型来使用,在java或C++中称为多态
class Dice{ let sides:Int let generatot:RandomNumberGenerator init(sides:Int,generator:RandomNumberGenerator){ self.sides = sides self.generatot = generator } func roll() -> Int{ return Int(generatot.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6, generator: Linear()) //实例的时候不能实例协议,要实例遵守洗衣的类 for _ in 1...5 { print("\(d6.roll())") }
标签:
原文地址:http://my.oschina.net/u/2346786/blog/523452