本文介绍了在Swift中以Equatable和Printable作为参数的泛型函数和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何编写一个允许任何对象但在Swift中必须为对象的Printable
和Equatable
数组的函数?
How to write a function that allow any objects but must be Printable
and Equatable
array of objects in Swift?
class func withItems(items: [AnyObject]){
}
- 我需要将项目设置为
Printable
和Equatable
- 我需要将items数组声明为类的属性
谢谢
推荐答案
您可以使用泛型约束在一个函数中同时要求两个协议:
You can use generic constraints to require both protocols in a function:
class func withItems<T: AnyObject where T: Equatable, T: Printable>(items: [T]) {
// ...
}
因为Equatable
不能用作类型,所以要求具有存储属性的操作比较棘手.为此,您实际上需要使类本身具有通用性.最好将items
声明为AnyObject
的数组,并通过像这样的通用方法提供对它的访问.
Requiring that of a stored property is trickier, since Equatable
can't be used as a type. In order to do so you'd essentially need to make the class itself generic. You'd probably be better off declaring items
as an array of AnyObject
and providing access to it through generic methods like this one.
这篇关于在Swift中以Equatable和Printable作为参数的泛型函数和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!