Reputation: 93
I am working on one of the examples in The Swift Programming Language book related to Optional Protocol Requirements. I have a problem in the following code.
import Foundation
@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
@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
}
}
}
class ThreeSource: CounterDataSource {
var fixedIncrement = 3
}
var counter = Counter()
counter.dataSource = ThreeSource()
for _ in 1...4 {
counter.increment()
println(counter.count)
}
Shouldn't this work? The println()
continuously outputs 0, when it should be incrementing by 3s.
Upvotes: 2
Views: 310
Reputation: 51911
@objc protocol
requires @objc
implementation.
In your case:
class ThreeSource: CounterDataSource {
@objc var fixedIncrement = 3
// ^^^^^ YOU NEED THIS!
}
without it, Objective-C runtime can't find the property.
Upvotes: 3