可选链接不适用于可选协议要求

时间:2015-04-28 18:50:42

标签: ios swift optional

我正在关注Apple的this example,并且可选链接无法按预期工作。

有一个带有可选属性和功能的协议:

@objc protocol CounterDataSource {
  optional func incrementForCount(count: Int) -> Int
  optional var fixedIncrement: Int { get }
}

符合上述协议的类:

class ThreeSource: CounterDataSource {
  let fixedIncrement = 3
}

具有符合该协议的可选属性(dataSource)的类:

@objc class Counter {
  var count = 0
  var dataSource: CounterDataSource?
  func increment() {
    if let amount = dataSource?.incrementForCount?(count) {
        count += amount
    } else if let amount = dataSource?.fixedIncrement {
        count += amount
    }
  }
}

最后,当使用具有非零数据源属性的Counter实例时,它的行为不符合预期:

var counter = Counter()
counter.dataSource = ThreeSource()
  for _ in 1...4 {
    counter.increment()
    println(counter.count)
  }

如果我没错,根据教程,我们应该打印3,6,9,12。但我只得到0,0,0,0。

这是类Counter中的可选链接,预计会将值3(由于ThreeSource中的fixedIncrement属性)赋值为:

        } else if let amount = dataSource?.fixedIncrement {
        count += amount
    }

但是这不起作用,并且不执行该分支。

代码有什么问题吗?或者这可能是一个错误?

1 个答案:

答案 0 :(得分:0)

事实证明,The Swift Programming Language(https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html)的iBook内容的网站版本显示了使用@objc声明的ThreeSource。无论是这样做还是从NSObject派生出ThreeSource都可以。

enter image description here

相关问题