首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >键入'className -> () -> className!‘不符合协议

键入'className -> () -> className!‘不符合协议
EN

Stack Overflow用户
提问于 2014-06-06 07:15:48
回答 4查看 3.8K关注 0票数 3

我在和斯威夫特胡闹。我有一个协议被定义为

代码语言:javascript
复制
protocol timerProtocol {
    func timerFired()
}

持有对委托的引用的类

代码语言:javascript
复制
class Stopwatch: NSObject {
    var delegate: protocol <timerProtocol>

    init(delegate: protocol <timerProtocol> ) {
        self.delegate = delegate
    }

...
}

和一个实现该协议的类

代码语言:javascript
复制
class StopwatchesTableViewController: UITableViewController, timerProtocol {

    func timerFired() {
        println("timer");
    }

    let stopwatch = Stopwatch(delegate: self) // Error here

...
}

声明秒表时出现错误--“类型'StopwatchesTableViewController -> () -> StopwatchesTableViewController!‘不符合协议'timerProtocol'”

如何解决此问题?

EN

回答 4

Stack Overflow用户

发布于 2014-06-06 08:27:12

更改var delegate: protocol <timerProtocol>

转到var delegate: timerProtocol?

票数 1
EN

Stack Overflow用户

发布于 2014-06-22 20:03:19

从语法和逻辑上讲,这对我来说就像一个护身符:

代码语言:javascript
复制
protocol TimerProtocol {
    func timerFired()
}

class Stopwatch {
    var delegate: protocol <TimerProtocol>? = nil
    
    init() { }
    
    convenience init(delegate: protocol <TimerProtocol> ) {
        self.init()
        self.delegate = delegate
    }

}

class StopwatchesTableViewController: UITableViewController, TimerProtocol {
    
    @lazy var stopwatch: Stopwatch = Stopwatch()
    
    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        stopwatch.delegate = self
    }
    
    func timerFired() {
        println("timer");
    }

}

注意:协议的名称应以大写字母开头。

StopwatchesTableViewController类将如下所示:

代码语言:javascript
复制
class StopwatchesTableViewController: UITableViewController, TimerProtocol {
    
    var stopwatch: Stopwatch? = nil
    
    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        stopwatch = Stopwatch(delegate: self)
    }
    
    func timerFired() {
        println("timer");
    }

}
票数 1
EN

Stack Overflow用户

发布于 2014-06-06 08:13:43

试着改变,

代码语言:javascript
复制
let stopwatch = Stopwatch(delegate: self) // Error here

代码语言:javascript
复制
@lazy var stopwatch: Stopwatch = Stopwatch(delegate: self)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24071730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档