swift学习

Swift5.1 - 协议(10)

2019-07-31  本文已影响18人  HChase

协议(Protocol)

protocol Behaviour {
    func run()
    var age: Int { set get }
    var height: Int {get}
    subscript(index: Int) -> Int { get set}
}
protocol Behaviour1 {}
protocol Behaviour2 {}
protocol Behaviour3 {}

class Animal: Behaviour1, Behaviour2, Behaviour3 {
    
}

协议的属性

static 、class

protocol Behaviour {
    static var height: Int {get}
}

class Animal: Behaviour {
    class var height: Int {
        return 10
    }
}

mutating

protocol Behaviour {
    mutating func run()
}

struct Animal: Behaviour {
    func run() {
        
    }
}

init

protocol Behaviour {
    init(age: Int, name: String)
}

class Animal: Behaviour {
    required init(age: Int, name: String) {
        // ...
    }
}

final class Person: Behaviour {
    init(age: Int, name: String) {
        // ...
    }
}

协议的继承

protocol Behaviour {
    func run()
    subscript(index: Int) -> Int {get}
}

protocol SubBehaviour: Behaviour {
    func eat()
}

class Animal: SubBehaviour {
    subscript(index: Int) -> Int {
        return 10
    }
    
    func eat() {
        //...
    }
    
    func run() {
        //...
    }
}

协议的组合

protocol Drawable {}
protocol Runnable {}
class Person {}

// 接收Person或其子类的实例
func test1(obj: Person) {}

// 接收遵守Drawable协议的实例
func test2(obj: Drawable) {}

// 接收遵守 Drawable与Runnable 协议的实例
func test3(obj: Drawable & Runnable) {}

// 接收遵守 Drawable与Runnable 协议,并且是Person或其子类的实例
func test4(obj: Person & Drawable & Runnable) {}

CaseIterable

enum Test : CaseIterable {
    case a, b, c, d
}

let cases = Test.allCases
print(cases.count)  // 4
for c in cases {
    print(c)
}  // a、b、c、d
上一篇 下一篇

猜你喜欢

热点阅读