ios - View Controller only 协议无权访问 View Controller 属性
问题描述
我只有一个UIViewController
协议
protocol VCProtocol where Self: UIViewController {}
我有一个带VCProtocol
参数的函数。在函数内部,我无法访问任何属性UIViewController
func testFunction(vcProtocol: VCProtocol) {
// vcProtocol.view ‼️ error: Value of type 'VCProtocol' has no member 'view'
}
虽然我可以将协议参数转换为UIViewController
然后访问属性,如下所示:
func testFunction(vcProtocol: VCProtocol) {
(vcProtocol as! UIViewController).view
}
这是方法吗?我们有更好的办法吗?
解决方案
您可以使用&
运算符来组合协议
protocol VCProtocol where Self: UIViewController {}
func testFunction(vcProtocol: VCProtocol & UIViewController) {
let view = vcProtocol.view
}
推荐阅读
- python - 为什么在使用数组迭代和提取元素时在列表中打印数组([])?
- c++ - 修改 QDockWidget 默认捕捉位置?
- c# - 通过弹出窗口输出 HTTP 状态码
- jquery - 使用 Bootbox Confirm,在哪里放置 preventDefault?
- excel - MS Access 查询到 Excel,“参数太少。应为 1”
- c# - 如何获取拆分的剩余内容?
- nativescript - 使用 Nativescript 在外部浏览器中打开某些链接
- sql - 从两个id不相同的表中获取用户
- apache-kafka - 使用 JMX 监控旧消费者组的 Kafka 日志偏移量
- python - 运行 OpenCV 画线脚本时遇到错误