DAB
DAB

Reputation: 93

Optional Protocol Requirements, I Can't Get It To Work

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

Answers (1)

rintaro
rintaro

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

Related Questions