声明符合 Swift 中协议的 UIView 类型的变量 2

Declare variable of type UIView conforming to a protocol in Swift 2

我需要声明一个 UIView 类型的变量,它也符合 MyProtocol:

protocol MyProtocol: class {
    func foobar()
}

class MyClass {
    var myView: UIView<MyProtocol>! // Error: Cannot specialize non-generic type 'UIView'
}

但是我收到编译器错误:无法专门化非泛型类型 'UIView'。

我需要访问来自 UIViewMyProtocol 的变量的方法。

支持这些要求的正确变量声明是什么?

如果有任何区别,只有 UIView 个子类会实现该协议。目前我通过扩展添加协议一致性。

我找到了这个答案: 但不清楚这个答案是否仍然是写 Swift 2.

时的最佳选择

按如下方式将您的 class 设为通用 class,

protocol MyProtocol: class {
    func foobar()
}

class MyClass<T:MyProtocol where T:UIView> {
    var myView: T!
}

上面的错误表明 UIView 无法专门针对 MyProtocol 协议,因此,这里的解决方案是使您的 class 成为通用的 class,它采用符合 MyProtocol 的通用参数并且是 sub class 个 UIView。

可能解决这个问题的最好方法是使用所有 UIViews 都符合的协议:

protocol UIViewType {
    var view: UIView { get }
}

extension UIView: UIViewType {
    var view: UIView { return self }
}

// the variable
var myView: protocol<UIViewType, MyProtocol>

使用 view 属性 访问 UIView 特定功能。

晚会晚了,但是 SE-0156(被 Swift 4 采用)在类型声明中启用了 class 和协议组合,而不需要(求助于?)泛型。

protocol MyProtocol: class {
     func foobar()
}

class MyClass {
     var myView: (UIView & MyProtocol)!
}

If it makes any difference, only UIView subclasses will implement the protocol.

一切都不同了!只需这样做:

protocol MyProtocol: UIView {
  func foobar()
}

class MyClass {
  var myView: MyProtocol!
}