首页 > 解决方案 > 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
}

这是方法吗?我们有更好的办法吗?

标签: iosswift

解决方案


您可以使用&运算符来组合协议

protocol VCProtocol where Self: UIViewController {}

func testFunction(vcProtocol: VCProtocol & UIViewController) {
    let view = vcProtocol.view
}

推荐阅读