swift - 符合协议(protocol)的类作为 Swift 中的函数参数

标签 swift

在 Objective-C 中,可以将符合协议(protocol)的类指定为方法参数。例如,我可以有一个只允许 UIViewController 的方法。符合 UITableViewDataSource :

- (void)foo:(UIViewController<UITableViewDataSource> *)vc;

我找不到在 Swift 中执行此操作的方法(也许现在还不可能)。您可以使用 func foo(obj: protocol<P1, P2>) 指定多个协议(protocol),但是您如何要求该对象也属于特定类?

最佳答案

您可以将 foo 定义为通用函数,并使用类型约束来要求类和协议(protocol)。

swift 4

func foo<T: UIViewController & UITableViewDataSource>(vc: T) {
    .....
}

Swift 3(也适用于 Swift 4)

func foo<T: UIViewController>(vc:T) where T:UITableViewDataSource { 
    ....
}

swift 2

func foo<T: UIViewController where T: UITableViewDataSource>(vc: T) {
    // access UIViewController property
    let view = vc.view
    // call UITableViewDataSource method
    let sections = vc.numberOfSectionsInTableView?(tableView)
}

关于swift - 符合协议(protocol)的类作为 Swift 中的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666838/

相关文章:

swift - 如何声明具有两种可能类型的变量

ios - 在 UITableViewHeaderFooterView 中有一个按钮

ios - RxSwift - 在 X 秒内未收到元素后发出

ios - 让多个 IF 语句子句协同工作

ios - iPad 未连接它显示操作系统版本

swift - 如何检查当前用户是否是 Realm SyncUser 的管理员?

ios - 使用alamofire上传图片

ios - ‘无法在属性初始值设定项中使用实例成员 ‘allEvents’;属性初始值设定项在 ‘self’ 可用之前运行’错误

json - Swift:解析数据 Codable 协议(protocol)不起作用

ios - 使用破坏性样式和 UIAlertAction 删除按钮