【问题标题】:Type 'className -> () -> className!' does not conform to protocol键入“类名 -> () -> 类名!”不符合协议
【发布时间】:2014-06-05 23:15:48
【问题描述】:

我在玩 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

...
}

我在声明秒表时遇到错误 - “Type 'StopwatchesTableViewController -> () -> StopwatchesTableViewController!'不符合协议'timerProtocol'"

我该如何解决这个问题?

【问题讨论】:

  • 您不能将self 引用为实例直到该实例不存在。

标签: protocols swift


【解决方案1】:

更改var delegate: protocol &lt;timerProtocol&gt;

var delegate: timerProtocol?

【讨论】:

    【解决方案2】:

    从句法和逻辑上来说,这对我来说就像一个魅力:

    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 类看起来像例如这个:

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

    【讨论】:

      【解决方案3】:

      尝试改变,

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

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

      【讨论】:

        【解决方案4】:

        你的代码

        let stopwatch = Stopwatch(delegate: self)
        

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

        你需要做的

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-24
          • 2019-11-23
          • 2018-07-12
          • 2023-03-24
          • 1970-01-01
          相关资源
          最近更新 更多