《Swift从入门到精通》(十八):协议

协议(学习笔记)

环境Xcode 11.0 beta4 swift 5.1

  • 协议语法

    • 示例

      protocol SomeProtocol {
          // protocol definition goes here
      }
      struct SomeStructure: FirstProtocol, AnotherProtocol {
          // structure definition goes here
      }
      class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
          // class definition goes here
      }
      
      
  • 属性要求

    • 协议不需指定属性是存储或计算属性,只需指定所需的属性名称和类型;协议指定了每个属性是可读或可读可写,通常在类型后跟 {get set}{ get } 标识

      protocol SomeProtocol {
          var mustBeSettable: Int { get set }
          var doesNotNeedToBeSettable: Int { get }
      }
      
      
    • 协议中类型属性仍然用关键字 staticclass 修饰

      protocol AnotherProtocol {
          static var someTypeProperty: Int { get set }
      }
      
      
      // 只有一个属性的协议
      protocol FullyNamed {
          var fullName: String { get }
      }
      // 遵守协议必需要提供一个一个名为 fullName 的可获取实例属性
      struct Person: FullyNamed {
          var fullName: String
      }
      let john = Person(fullName: "John Appleseed")
      // john.fullName is "John Appleseed"
      // 
      // 遵守 FullNamed 协议,此处用的是一个只可读的计算属性
      class Starship: FullyNamed {
          var prefix: String?
          var name: String
          init(name: String, prefix: String? = nil) {
              self.name = name
              self.prefix = prefix
          }
          var fullName: String {
              return (prefix != nil ? prefix! + " " : "") + name
          }
      }
      var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
      // ncc1701.fullName is "USS Enterprise"
      
      
  • 方法要求

    • 协议定义中可定义实例和类型方法,与正常的方法定义类似,方法参数可以是可变参数,但不能有方法体,且参数不能设置默认值

      protocol SomeProtocol {
          static func someTypeMethod()
      }
      protocol RandomNumberGenerator {
          func random() -> Double
      }
      // 示例如下
      class LinearCongruentialGenerator: RandomNumberGenerator {
          var lastRandom = 42.0
          let m = 139968.0
          let a = 3877.0
          let c = 29573.0
          func random() -> Double {
              lastRandom = ((lastRandom * a + c)
                  .truncatingRemainder(dividingBy:m))
              return lastRandom / m
          }
      }
      let generator = LinearCongruentialGenerator()
      print("Here's a random number: \(generator.random())")
      // Prints "Here's a random number: 0.3746499199817101"
      print("And another one: \(generator.random())")
      // Prints "And another one: 0.729023776863283"
      
      
  • 可变方法要求

    • 协议中方法可用 mutatuing 修饰,这位遵守此协议的方法可以修改属性值(结构体、枚举也可以),且可在实现方法时可省略此关键字

      protocol Togglable {
          mutating func toggle()
      }
      enum OnOffSwitch: Togglable {
          case off, on
          mutating func toggle() {
              switch self {
              case .off:
                  self = .on
              case .on:
                  self = .off
              }
          }
      }
      var lightSwitch = OnOffSwitch.off
      lightSwitch.toggle()
      // lightSwitch is now equal to .on
      
      
  • 初始化器要求

    • 协议中可定义初始化器让遵守的类型实现,但协议中的初始化器没有 {} 或 函数体,实现类实现初始化器(便捷或指定初始化器)必需加 required 修饰符

      protocol SomeProtocol {
          init(someParameter: Int)
      }
      class SomeClass: SomeProtocol {
          required init(someParameter: Int) {
              // initializer implementation goes here
          }
      }
      
      
    • 如果一个子类重写父类的指定初始化器同时遵守协议的初始化器的要求,必需同时用 requiredoverride 修饰符

      protocol SomeProtocol {
          init()
      }
      //
      class SomeSuperClass {
          init() {
              // initializer implementation goes here
          }
      }
      //
      class SomeSubClass: SomeSuperClass, SomeProtocol {
          // "required" from SomeProtocol conformance; "override" from SomeSuperClass
          required override init() {
              // initializer implementation goes here
          }
      }
      
      
  • 协议作为类型

    • 可以做参数类型、函数返回值、方法返回值、初始化器返回值类型

    • 可以做常量、变量、属性的类型

    • 可以用在字典、数组、其它容器中元素的类型

      class Dice {
          let sides: Int
          let generator: RandomNumberGenerator
          init(sides: Int, generator: RandomNumberGenerator) {
              self.sides = sides
              self.generator = generator
          }
          func roll() -> Int {
              return Int(generator.random() * Double(sides)) + 1
          }
      }
      var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
      for _ in 1...5 {
          print("Random dice roll is \(d6.roll())")
      }
      // Random dice roll is 3
      // Random dice roll is 5
      // Random dice roll is 4
      // Random dice roll is 5
      // Random dice roll is 4
      
      
  • 代理

    • 代理是一种重要的设计模式,示例代码

      protocol DiceGame {
          var dice: Dice { get }
          func play()
      }
      protocol DiceGameDelegate: AnyObject {
          func gameDidStart(_ game: DiceGame)
          func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
          func gameDidEnd(_ game: DiceGame)
      }
      class SnakesAndLadders: DiceGame {
          let finalSquare = 25
          let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
          var square = 0
          var board: [Int]
          init() {
              board = Array(repeating: 0, count: finalSquare + 1)
              board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
              board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
          }
          weak var delegate: DiceGameDelegate? // 一般用 weak
          func play() {
              square = 0
              delegate?.gameDidStart(self)
              gameLoop: while square != finalSquare {
                  let diceRoll = dice.roll()
                  delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)
                  switch square + diceRoll {
                  case finalSquare:
                      break gameLoop
                  case let newSquare where newSquare > finalSquare:
                      continue gameLoop
                  default:
                      square += diceRoll
                      square += board[square]
                  }
              }
              delegate?.gameDidEnd(self)
          }
      }
      class DiceGameTracker: DiceGameDelegate {
          var numberOfTurns = 0
          func gameDidStart(_ game: DiceGame) {
              numberOfTurns = 0
              if game is SnakesAndLadders {
                  print("Started a new game of Snakes and Ladders")
              }
              print("The game is using a \(game.dice.sides)-sided dice")
          }
          func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {
              numberOfTurns += 1
              print("Rolled a \(diceRoll)")
          }
          func gameDidEnd(_ game: DiceGame) {
              print("The game lasted for \(numberOfTurns) turns")
          }
      }
      let tracker = DiceGameTracker()
      let game = SnakesAndLadders()
      game.delegate = tracker
      game.play()
      // Started a new game of Snakes and Ladders
      // The game is using a 6-sided dice
      // Rolled a 3
      // Rolled a 5
      // Rolled a 4
      // Rolled a 5
      // The game lasted for 4 turns
      
      
  • 用扩展添加协议的一致性

    • 扩展可以为现有的类添加属性、方法、下标,因此可以添加协议可能需要的任何要求

      protocol TextRepresentable {
          var textualDescription: String { get }
      }
      extension Dice: TextRepresentable {
          var textualDescription: String {
              return "A \(sides)-sided dice"
          }
      }
      let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator())
      print(d12.textualDescription)
      // Prints "A 12-sided dice"
      extension SnakesAndLadders: TextRepresentable {
          var textualDescription: String {
              return "A game of Snakes and Ladders with \(finalSquare) squares"
          }
      }
      print(game.textualDescription)
      // Prints "A game of Snakes and Ladders with 25 squares"
      
      
    • 有条件的遵守协议

      // Array 中的元素要遵守  TextRepresentable 协议
      extension Array: TextRepresentable where Element: TextRepresentable {
          var textualDescription: String {
              let itemsAsText = self.map { $0.textualDescription }
              return "[" + itemsAsText.joined(separator: ", ") + "]"
          }
      }
      let myDice = [d6, d12]
      print(myDice.textualDescription)
      // Prints "[A 6-sided dice, A 12-sided dice]"
      
      
    • 采用扩展申明协议

      struct Hamster {
          var name: String
          var textualDescription: String {
              return "A hamster named \(name)"
          }
      }
      extension Hamster: TextRepresentable {}
      let simonTheHamster = Hamster(name: "Simon")
      // 这里要显示申明类型
      let somethingTextRepresentable: TextRepresentable = simonTheHamster
      print(somethingTextRepresentable.textualDescription)
      // Prints "A hamster named Simon"
      
      
  • 协议类型集合

    • 示例

      let things: [TextRepresentable] = [game, d12, simonTheHamster]
      for thing in things {
          print(thing.textualDescription)
      }
      // A game of Snakes and Ladders with 25 squares
      // A 12-sided dice
      // A hamster named Simon
      
      
  • 协议继承

    • 示例

      protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
          // protocol definition goes here
      }
      protocol PrettyTextRepresentable: TextRepresentable {
          var prettyTextualDescription: String { get }
      }
      extension SnakesAndLadders: PrettyTextRepresentable {
          var prettyTextualDescription: String {
              var output = textualDescription + ":\n"
              for index in 1...finalSquare {
                  switch board[index] {
                  case let ladder where ladder > 0:
                      output += "▲ "
                  case let snake where snake < 0:
                      output += "▼ "
                  default:
                      output += "○ "
                  }
              }
              return output
          }
      }
      print(game.prettyTextualDescription)
      // A game of Snakes and Ladders with 25 squares:
      // ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○
      
      
  • Class-Only 协议

    • 可以限制协议只能类来遵守,通过添加 AnyObject 协议在继承列表中,如果结构体或枚举遵守会报运行时错误

      protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
          // class-only protocol definition goes here
      }
      
      
  • 协议合成

    • & 符号将多个协议连接起来

      protocol Named {
          var name: String { get }
      }
      protocol Aged {
          var age: Int { get }
      }
      struct Person: Named, Aged {
          var name: String
          var age: Int
      }
      func wishHappyBirthday(to celebrator: Named & Aged) {
          print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
      }
      let birthdayPerson = Person(name: "Malcolm", age: 21)
      wishHappyBirthday(to: birthdayPerson)
      // Prints "Happy birthday, Malcolm, you're 21!"
      //
      //
      class Location {
          var latitude: Double
          var longitude: Double
          init(latitude: Double, longitude: Double) {
              self.latitude = latitude
              self.longitude = longitude
          }
      }
      class City: Location, Named {
          var name: String
          init(name: String, latitude: Double, longitude: Double) {
              self.name = name
              super.init(latitude: latitude, longitude: longitude)
          }
      }
      func beginConcert(in location: Location & Named) {
          print("Hello, \(location.name)!")
      }
      let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3)
      beginConcert(in: seattle)
      // Prints "Hello, Seattle!"
      
      
  • 协议一致性检查

    • is 实例遵守协议返回 true, 否则 false

    • as? 返回一个协议类型的可选值,如果不遵守协议则是 nil

    • as! 强制解包,如果失败触发运行时错误

      protocol HasArea {
          var area: Double { get }
      }
      class Circle: HasArea {
          let pi = 3.1415927
          var radius: Double
          var area: Double { return pi * radius * radius }
          init(radius: Double) { self.radius = radius }
      }
      class Country: HasArea {
          var area: Double
          init(area: Double) { self.area = area }
      }
      class Animal {
          var legs: Int
          init(legs: Int) { self.legs = legs }
      }
      let objects: [AnyObject] = [
          Circle(radius: 2.0),
          Country(area: 243_610),
          Animal(legs: 4)
      ]
      for object in objects {
          if let objectWithArea = object as? HasArea {
              print("Area is \(objectWithArea.area)")
          } else {
              print("Something that doesn't have an area")
          }
      }
      // Area is 12.5663708
      // Area is 243610.0
      // Something that doesn't have an area
      
      
  • 可选协议要求

    • optional 修饰,协议和可选需求都必需用 @objc 标记,被标记的协议只能是OC类或其它 @objc类可用,枚举结构体不可用

      @objc protocol CounterDataSource {
          @objc optional func increment(forCount count: Int) -> Int
          @objc optional var fixedIncrement: Int { get }
      }
      class Counter {
          var count = 0
          var dataSource: CounterDataSource?
          func increment() {
              if let amount = dataSource?.increment?(forCount: count) {
                  count += amount
              } else if let amount = dataSource?.fixedIncrement {
                  count += amount
              }
          }
      }
      class ThreeSource: NSObject, CounterDataSource {
          let fixedIncrement = 3
      }
      var counter = Counter()
      counter.dataSource = ThreeSource()
      for _ in 1...4 {
          counter.increment()
          print(counter.count)
      }
      // 3
      // 6
      // 9
      // 12
      class TowardsZeroSource: NSObject, CounterDataSource {
          func increment(forCount count: Int) -> Int {
              if count == 0 {
                  return 0
              } else if count < 0 {
                  return 1
              } else {
                  return -1
              }
          }
      }
      counter.count = -4
      counter.dataSource = TowardsZeroSource()
      for _ in 1...5 {
          counter.increment()
          print(counter.count)
      }
      // -3
      // -2
      // -1
      // 0
      // 0
      
      
  • 协议扩展

    • 可以为协议添加扩展,扩展里可以添加方法、计算属性、下标、初始化器等,这样类型的一致性或全局函数的行为可在此实现

      extension RandomNumberGenerator {
          func randomBool() -> Bool {
              return random() > 0.5
          }
      }
      let generator = LinearCongruentialGenerator()
      print("Here's a random number: \(generator.random())")
      // Prints "Here's a random number: 0.3746499199817101"
      print("And here's a random Boolean: \(generator.randomBool())")
      // Prints "And here's a random Boolean: true"
      
      
    • 提供默认的实现

      extension PrettyTextRepresentable  {
          var prettyTextualDescription: String {
              return textualDescription
          }
      }
      
      
    • 协议扩展添加约束

      extension Collection where Element: Equatable {
          func allEqual() -> Bool {
              for element in self {
                  if element != self.first {
                      return false
                  }
              }
              return true
          }
      }
      let equalNumbers = [100, 100, 100, 100, 100]
      let differentNumbers = [100, 100, 200, 100, 200]
      print(equalNumbers.allEqual())
      // Prints "true"
      print(differentNumbers.allEqual())
      // Prints "false"
      
      
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343

推荐阅读更多精彩内容