Additional protocol requirements, I can't get it to work

I am working on one example in the Swift Programming Language book related to additional 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)
}

Doesn't that work? println()continuously outputs 0 when it should increase by 3 s.

+2
source share
1 answer

@objc protocolimplementation required @objc.

In your case:

class ThreeSource: CounterDataSource {
    @objc var fixedIncrement = 3
//  ^^^^^ YOU NEED THIS!
}

without it, the Objective-C runtime cannot find a property.

+3
source

Source: https://habr.com/ru/post/1678342/


All Articles