协议扩展编译器错误中的Swift 2.2 #selector [英] Swift 2.2 #selector in protocol extension compiler error

查看:116
本文介绍了协议扩展编译器错误中的Swift 2.2 #selector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个协议扩展,它曾经在swift 2.2之前完美运行。

I've got a protocol extension it used to work perfectly before swift 2.2.

现在我有一个警告告诉我使用新的 #selector ,但是如果我添加它

Now I have a warning that tells me to use the new #selector, but if I add it


没有使用Objective-C Selector声明的方法。

no method declared with Objective-C Selector.

我尝试在这几行代码中重现这个问题,可以很容易地复制并粘贴到游乐场

I tried to reproduce the issue in this few lines of code, that can be easily copy and paste also into playground

  protocol Tappable {
    func addTapGestureRecognizer()
    func tapGestureDetected(gesture:UITapGestureRecognizer)
}

extension Tappable where Self: UIView {
    func addTapGestureRecognizer() {
        let gesture = UITapGestureRecognizer(target: self, action:#selector(Tappable.tapGestureDetected(_:)))
        addGestureRecognizer(gesture)
    }
}

class TapView: UIView, Tappable {
    func tapGestureDetected(gesture:UITapGestureRecognizer) {
        print("Tapped")
    }
}

还有一个建议要附加到该方法中协议 @objc ,但如果我这样做也要求我将它添加到实现它的类中,但是一旦我添加了类就不再符合协议了,因为它似乎没有看到协议扩展中的实现。


如何正确实现?

There is also a suggestion to append to that method in the protocol @objc, but if I do it asks me also to add it to the class that implements it, but once I add the class doesn't conform to the protocol anymore, because it doesn't seems to see the implementation in the protocol extension.
How can I implement this correctly?

推荐答案

我遇到了类似的问题。这就是我所做的。

I had a similar problem. here is what I did.


  1. 将协议标记为@objc。

  2. 标记任何方法我使用默认行为扩展为可选。

  3. 然后使用Self。在#selector中。

  1. Marked the protocol as @objc.
  2. Marked any methods I extended with a default behavior as optional.
  3. Then used Self. in the #selector.

@objc public protocol UpdatableUserInterfaceType {
  optional func startUpdateUITimer()
  optional var updateInterval: NSTimeInterval { get }
  func updateUI(notif: NSTimer)
}

public extension UpdatableUserInterfaceType where Self: ViewController {

  var updateUITimer: NSTimer {
    return NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: #selector(Self.updateUI(_:)), userInfo: nil, repeats: true)
  }

  func startUpdateUITimer() {
    print(updateUITimer)
  }

  var updateInterval: NSTimeInterval {
    return 60.0
  }
}


这篇关于协议扩展编译器错误中的Swift 2.2 #selector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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