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

时间秒杀一切 提交于 2020-01-24 19:31:07

问题


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.


回答1:


@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.



来源:https://stackoverflow.com/questions/31478562/optional-protocol-requirements-i-cant-get-it-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!