简体   繁体   English

符合通用函数中使用的协议和类的类型的变量

[英]Variable of type that conforms to protocol and class used in generic function

I want to declare a variable 我想声明一个变量

var specialVC: UIViewController & MyProtocol.

And I have a function 我有一个功能

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

However, when I try to pass in my variable into the doStuff, it says UIViewController doesn't conform to 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) {}

}

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

--- Update --- -更新-

After looking at Protocol doesn't conform to itself? 看完协议后不符合自身? , I am able to create an extension that specifies a class that conforms to a protocol. ,我能够创建一个扩展,该扩展指定一个符合协议的类。 However, I won't be able to call doStuff() from this extension. 但是,我将无法从此扩展程序调用doStuff()。

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

There is nothing about your function that needs to be a generic. 关于您的功能,没有什么需要通用的。 Just use the normal types-and-supertypes mechanism (polymorphism, inheritance, whatever you like to call it). 只需使用常规的类型和超类型机制(多态性,继承,无论您喜欢用哪种方式)。 Just type your parameter as the supertype; 只需输入您的参数作为超类型即可; this tells the compiler that it inherits all features of the supertype. 这告诉编译器它继承了超类型的所有功能。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM