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

编程入门 行业动态 更新时间:2024-10-23 19:28:18
本文介绍了符合协议的类作为 Swift 中的函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 中的函数参数

本文发布于:2023-11-26 20:16:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   协议   参数   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!