符合协议的类作为 Swift 中的函数参数

符合协议的类作为 Swift 中的函数参数

问题描述:

在 Objective-C 中,可以将符合协议的类指定为方法参数.例如,我可以有一个方法,它只允许符合 UITableViewDataSourceUIViewController :

In Objective-C, it's possible to specify a class conforming to a protocol as a method parameter. For example, I could have a method that only allows a UIViewController that conforms to UITableViewDataSource:

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

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

I can't find a way to do this in Swift (perhaps it's not possible yet). You can specify multiple protocols using func foo(obj: protocol<P1, P2>), but how do you require that the object is of a particular class as well?

您可以将 foo 定义为泛型函数,并使用类型约束来要求类和协议.

You can define foo as a generic function and use type constraints to require both a class and a protocol.

Swift 4

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

Swift 3(也适用于 Swift 4)

Swift 3 (works for Swift 4 also)

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)
}