I'm following this example from Apple and the optional chaining does not work as expected.
There is a protocol with optional property and function:
@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
A class that conform to above protocol:
class ThreeSource: CounterDataSource {
let fixedIncrement = 3
}
And a class with an optional property (dataSource) that conforms to that protocol:
@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
}
}
}
Finally when it comes the time to use an instance of Counter, with a non-nil dataSource property, it doesn't behave as expected:
var counter = Counter()
counter.dataSource = ThreeSource()
for _ in 1...4 {
counter.increment()
println(counter.count)
}
If I'm not wrong and according to the tutorial, we should get printed 3, 6, 9, 12. But I only get 0, 0, 0, 0.
Here is the optional chaining in class Counter that is expected to be assigning the value 3 (due to the fixedIncrement property in ThreeSource) to amount:
} else if let amount = dataSource?.fixedIncrement {
count += amount
}
However this is not working and that branch is not executed.
Is there anything wrong in the code? Or is this maybe a bug?
It turns out that the website version of the iBook content for The Swift Programming Language (https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html) shows the ThreeSource declared with @objc. Either doing this or deriving ThreeSource from NSObject
works.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments