可选协议要求,我无法正常使用 [英] Optional Protocol Requirements, I Can't Get It To Work

查看:81
本文介绍了可选协议要求,我无法正常使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Swift编程语言书中与可选协议要求有关的示例之一.我的以下代码有问题.

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)
}

这行不行吗? println()在应增加3s时连续输出0.

Shouldn't this work? The println() continuously outputs 0, when it should be incrementing by 3s.

推荐答案

@objc protocol需要实现@objc.

在您的情况下:

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

没有它,Objective-C运行时找不到该属性.

without it, Objective-C runtime can't find the property.

这篇关于可选协议要求,我无法正常使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆