Protocols 类型';类名->;()->;类名';不符合协议
我在和斯威夫特鬼混。我有一个协议定义为Protocols 类型';类名->;()->;类名';不符合协议,protocols,swift,Protocols,Swift,我在和斯威夫特鬼混。我有一个协议定义为 protocol timerProtocol { func timerFired() } 持有对委托的引用的类 class Stopwatch: NSObject { var delegate: protocol <timerProtocol> init(delegate: protocol <timerProtocol> ) { self.delegate = delegate
protocol timerProtocol {
func timerFired()
}
持有对委托的引用的类
class Stopwatch: NSObject {
var delegate: protocol <timerProtocol>
init(delegate: protocol <timerProtocol> ) {
self.delegate = delegate
}
...
}
声明秒表时出现错误-“键入'StopwatchesTableViewController->()->StopwatchesTableViewController!'不符合协议'timerProtocol'”
如何解决此问题?尝试更改
let stopwatch = Stopwatch(delegate: self) // Error here
到
更改
var委托:协议
到var委托:timerProtocol?
您的代码
let stopwatch=stopwatch(代理:self)
在类的范围内(不在func
内),因此self
引用类(不是实例)。该类不符合协议,仅符合其实例
你需要做什么
让秒表:秒表
func init(){
秒表=秒表(代表:自我)
}
从语法和逻辑上来说,这对我来说就像一个符咒:
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");
}
}
在实例不存在之前,不能将
自身
引用为实例。
@lazy var stopwatch: Stopwatch = Stopwatch(delegate: self)
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");
}
}
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");
}
}