符合协议的类作为 Swift 中的函数参数 [英] Class conforming to protocol as function parameter in Swift

查看:29
本文介绍了符合协议的类作为 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)
}

这篇关于符合协议的类作为 Swift 中的函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆