swift

Swift中protocol

2019-06-29  本文已影响0人  盖小聂

1、将protocol的方法声明为mutating
2、Protocol Extension
3、可选接口和接口扩展
4、protocol组合
5、delegate

1、将protocol的方法声明为mutating
2、Protocol Extension
3、可选接口和接口扩展
@objc protocol OptionalProtocol {
optional func optionalMethod() //可选
func necessaryMethod() //必须
optional func anotherOptionalMethod() //可选
}
4、protocol组合
typealias PetLike = protocol<KittenLike, DogLike>
typealias CatLike = protocol<KittenLike, TigerLike>
protocol A {    
  func bar() —> Int
}

protocol B {    
  func bar() —> String
}

class Class: A, B {    

  func bar() —> Int 
  {       
    return 1    
  }    

  func bar() —> String{        
    return “Hi”    
  }
}

只要在调用前进行类型转换就可以了

let instance = Class()
let num = (instance as A).bar() //1
let str = (instance as B).bar() //“Hi”
5、delegate
@objc protocol MyClassDelegate {    
  func mehotd()  
}
protocol MyClassDelegate: class {    
  func method()
}
上一篇 下一篇

猜你喜欢

热点阅读