上QQ阅读APP看书,第一时间看更新
How to do it...
- Create a new playground file in Xcode called Protocols as usual.
- Complete the following example using the following protocol:
protocol VehicleProtocol{ // properties var name: String {set get} // settable and gettable var canFly: Bool {get} // gettable only (readonly) // instance methods func numberOfWheels() ->Int func move() func stop() // class method staticfuncpopularBrands() -> [String] } class Bicycle: VehicleProtocol{ var name: String var canFly: Bool{ return false } init(name: String){ self.name = name } func numberOfWheels() -> Int { return 2 } func move() { // move logic goes here } func stop() { // stop logic goes here } static func popularBrands() -> [String] { return ["Giant", "GT", "Marin", "Trek", "Merida", "Specialized"] } } class Car: VehicleProtocol{ var name: String var canFly: Bool{ return false } init(name: String){ self.name = name } funcnumberOfWheels() ->Int { return 4 } func move() { // move logic goes here } func stop() { // stop logic goes here } static func popularBrands() -> [String] { return ["Audi", "BMW", "Honda", "Dodge", "Lamborghini", "Lexus"] } } let bicycle1 = Bicycle(name: "Merida 204") bicycle1.numberOfWheels() // 2 let car1 = Car(name: "Honda Civic") car1.canFly // false Bicycle.popularBrands() // Class function // ["Giant", "GT", "Marin", "Trek", "Merida", "Specialized"] Car.popularBrands() // ["Audi", "BMW", "Honda", "Dodge", "Lamborghini", "Lexus"]