41

我有以下代码:

func registerNotification(name:String, selector:Selector)
{
    NSNotificationCenter.defaultCenter().addObserver(self, selector: selector, name: name, object: nil)
}

func registerKeyboardNotifications()
{
    let isInPopover = navigationController?.popoverPresentationController != nil
    let ignore = isInPopover && DEVICE_IS_IPAD
    if !ignore {
        registerNotification(UIKeyboardWillShowNotification, selector: Selector("keyboardWillShow:"))
        registerNotification(UIKeyboardWillHideNotification, selector: Selector("keyboardWillHide:"))
    }
}

在扩展至UIViewController. 许多视图控制器重用此代码来注册键盘通知。然而,对于 Swift 2.2,它会产生一个警告。我喜欢新#selector语法,但不确定在这种情况下如何实现它。

我认为正确的解决方案是制定一个协议并UIViewController仅针对符合该协议的实例进行扩展。到目前为止我的代码:

@objc protocol KeyboardNotificationDelegate
{
    func keyboardWillShow(notification: NSNotification)
    func keyboardWillHide(notification: NSNotification)
}

extension UIViewController where Self: KeyboardNotificationDelegate
{
    func registerKeyboardNotifications()
    {
        let isInPopover = navigationController?.popoverPresentationController != nil
        let ignore = isInPopover && DEVICE_IS_IPAD
        if !ignore {
            registerNotification(UIKeyboardWillShowNotification, selector: #selector(KeyboardNotificationDelegate.keyboardWillShow(_:)))
            registerNotification(UIKeyboardWillHideNotification, selector: #selector(KeyboardNotificationDelegate.keyboardWillHide(_:)))
        }
    }
}

然而,这让我得到了错误

trailing where clause for extension of non-generic type

在扩展行上。有任何想法吗?

4

2 回答 2

77

解决方案很简单,在扩展子句中切换顺序:

extension UIViewController where Self: KeyboardNotificationDelegate

应该

extension KeyboardNotificationDelegate where Self: UIViewController
于 2016-03-23T09:03:33.560 回答
23

extension Foo where ...只有在Foois时才能使用

  1. 泛型类或结构:使用符合某种类型约束的泛型的默认实现进行扩展,
  2. 一个包含一些关联类型的协议,当关联类型符合某种类型约束时,使用默认实现进行扩展
  3. 一个协议,我们使用默认实现扩展 whenSelf是特定(对象/引用)类型,或符合某种类型约束。

例如

// 1
class Foo<T> { }
extension Foo where T: IntegerType {}

struct Foz<T> {}
extension Foz where T: IntegerType {}

// 2
protocol Bar {
    associatedtype T
}
extension Bar where T: IntegerType {}

// 3
protocol Baz {}
extension Baz where Self: IntegerType {}

class Bax<T>: Baz {}
extension Baz where Self: Bax<Int> {
    func foo() { print("foo") }
}

let a = Bax<Int>()
a.foo() // foo

在您的情况下,UIViewController是一个非泛型类类型,它不符合上述任何一种。


正如您在自己的答案中所写,解决方案是使用默认实现扩展您的委托协议Self: UIViewController,而不是尝试扩展UIViewController.

于 2016-03-23T09:04:08.183 回答