Swift 中协议的扩展的简单应用

2017-03-03  本文已影响72人  ziyouzhe4

参考:

  1. Swift面向协议编程初探
  2. 从 Swift 的面向协议编程说开去

根据下面的结构 设计类和协议

Paste_Image.png

//交通工具类
class Vehicle: NSObject {

    func run(v : Vehicle) {
        print("\(v)  is runing")
    } 
}

//动物类
class Animal: NSObject {
    
    func eat(v : Animal) {
        print("\(v)  is eating")
    }
    
}

//能飞的协议
protocol Flayable {
    
}

extension Flayable {
    
    func flay(f : Flayable) {
        print("\(f) is can flay")
    }
}

//能飞的协议
protocol PetType {
}

extension PetType {
    func pet(f : PetType) {
        print("\(f) is a pet")
    }
}

//鹦鹉  宠物 / 能飞  class默认遵守 CustomStringConvertible协议喔
class Parrot : Animal , PetType , Flayable
{
       override var description:String {    
        return "Parrot"
    }
}

使用:

  let yw = Parrot()
  yw.flay(f: yw)
  yw.pet(f: yw)


Paste_Image.png
上一篇 下一篇

猜你喜欢

热点阅读