在 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/