BooleanType上的swift协议扩展不能按预期工作

时间:2016-03-15 18:24:42

标签: swift swift-protocols

此代码来自 https://www.raywenderlich.com/109156/introducing-protocol-oriented-programming-in-swift-2

除了BooleanType部分

外,它主要起作用
import Foundation

protocol Bird: BooleanType {
  var name: String { get }
  var canFly: Bool { get }
}

protocol Flyable {
  var airspeedVelocity: Double { get }
}


struct Penguin: Bird {
  let name: String
  let canFly = false
}

struct SwiftBird: Bird, Flyable {
  var name: String { return "Swift \(version)" }
  let version: Double
  var airspeedVelocity: Double { return 2000.0 }
}


extension Bird where Self: Flyable {
  // Flyable birds can fly!
  var canFly: Bool { return true }
}

extension BooleanType where Self: Bird {
  var boolValue: Bool {
    return self.canFly
  }
}


let bunchaBirds: [Bird] = 
  [
  Penguin(name: "King Penguin"),
  SwiftBird(version: 2.0),
  ]

//Boolean Type works directly on struct or enum type
if Penguin(name: "King Penguin") {
  print("I can fly!")
} else {
  print("Guess I’ll just sit here :[")
}

for bird in bunchaBirds {
  print("")
  print("for bird \(bird.name) it can fly ? \(bird.canFly)")

  //this works
  if bird as BooleanType {

  //this also  works
  //if bird.boolValue {

  //but this fail, 
  //if bird {
      print("\(bird.name): I can fly!")
  } else {
      print("\(bird.name): Guess I’ll just sit here :[")
  }
}

当数组中的对象为Bird类型时,BooleanType根本不起作用。 你必须明确地使用它或使用bird.boolValue,这对我来说似乎很奇怪!!

0 个答案:

没有答案