ios - 符合泛型函数中使用的协议和类的类型变量
问题描述
我想声明一个变量
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?
}
解决方案
您的函数没有什么需要是通用的。只需使用正常的类型和超类型机制(多态性、继承,无论你喜欢怎样称呼它)。只需键入您的参数作为超类型;这告诉编译器它继承了超类型的所有特性。
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
}
推荐阅读
- bash - BASH/SH 中具有一个 READER 和多个 WRITER 的 FIFO
- python - 如何在满足某些条件的列表中找到第 n 个连续值的索引?
- java - 使用构建器映射对象时定义无效
- php - 响应具有意外的状态代码 0 在服务器上
- python - Pandas read_excel 在读取 excel 文件时给出 yes no
- java - 使用 HTTP POST 请求替代 AsyncTask,因为它已被弃用
- vue.js - 我无法显示注册数据
- python - 表单始终无效/无法分配实例
- c++ - 非虚拟接口习语是否不适用于纯虚函数?
- python - 熊猫检查数据框中的空值,除了一列