首页 > 解决方案 > 符合泛型函数中使用的协议和类的类型变量

问题描述

我想声明一个变量

var specialVC: UIViewController & MyProtocol.

我有一个功能

func doStuff<T: UIViewController & MyProtocol> { ... }

但是,当我尝试将我的变量传递给 doStuff 时,它说 UIViewController 不符合 MyProtocol。

class MyClass: UIViewController {

    override func viewDidLoad() {
      super.viewDidLoad()
      var specialVC: UIViewController & MyProtocol
      doStuff(specialVC)
    }

    func doStuff<T: UIViewController & MyProtocol>(_ vc: T) {}

}

错误: Argument type 'UIViewController' does not conform to expected type 'MyProtocol'

- - 更新 - -

看了之后Protocol 不符合自己?,我能够创建一个扩展来指定一个符合协议的类。但是,我将无法从此扩展中调用 doStuff()。

internal extension MyProtocol where Self: UIViewController {
     // call doStuff(self) here somehow?
}

标签: iosswiftgenericsprotocols

解决方案


您的函数没有什么需要是通用的。只需使用正常的类型和超类型机制(多态性、继承,无论你喜欢怎样称呼它)。只需键入您的参数作为超类型;这告诉编译器它继承了超类型的所有特性。

protocol MyProtocol : UIViewController { // Swift 5 syntax
    var thingy : String { get set }
}
class MyViewController : UIViewController, MyProtocol {
    var thingy = "howdy"
}
func doStuff(_ vc: MyProtocol) {
    print(vc.title) // legal, because we know it's a view controller
    print(vc.thingy) // legal, because we know it's a MyProtocol
}

推荐阅读