输入'className - > () - >班级名称!'不符合协议

时间:2014-06-05 23:15:48

标签: protocols swift

我正在搞乱Swift。我有一个协议定义为

protocol timerProtocol {
    func timerFired()
}

持有对代理

的引用的类
class Stopwatch: NSObject {
    var delegate: protocol <timerProtocol>

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

...
}

以及实现协议的类

class StopwatchesTableViewController: UITableViewController, timerProtocol {

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

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

...
}

我在宣布秒表时收到错误 - &#34;输入&#39; StopwatchesTableViewController - &gt; () - &gt; StopwatchesTableViewController&#39!;不符合协议&#39; timerProtocol&#39;&#34;

如何解决此问题?

4 个答案:

答案 0 :(得分:1)

更改var delegate: protocol <timerProtocol>

var delegate: timerProtocol?

答案 1 :(得分:1)

语法和逻辑上对我来说就像一个魅力:

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

}

注意:协议&#39;名称应以大写字母开头。

StopwatchesTableViewController类看起来像是这样:

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

}

答案 2 :(得分:0)

尝试更改,

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

@lazy var stopwatch: Stopwatch = Stopwatch(delegate: self)

答案 3 :(得分:0)

您的代码

let stopwatch = Stopwatch(delegate: self)

在类的范围内(不在func内),因此self指的是类(不是实例)。该类不符合协议,只符合其实例。

你需要做

let stopwatch: Stopwatch

func init() {
    stopwatch = Stopwatch(delegate: self)
}