Skip to main content
 首页 » 操作系统

ios之在 Swift 中以 Equatable 和 Printable 作为参数的通用函数和属性

2024年01月01日44dflying

如何在 Swift 中编写允许任何对象但必须是 Printable 和 Equatable 对象数组的函数?

class func withItems(items: [AnyObject]){ 
 
} 
  1. 我需要项目是Printable 和Equatable
  2. 我需要将 items 数组声明为我的类的属性

谢谢

请您参考如下方法:

您可以使用通用约束来要求函数中的两种协议(protocol):

class func withItems<T: AnyObject where T: Equatable, T: Printable>(items: [T]) { 
    // ... 
} 

要求存储属性的那个比较棘手,因为 Equatable 不能用作类型。为此,您基本上需要使类本身具有通用性。您最好将 items 声明为 AnyObject 的数组,并通过像这样的通用方法提供对它的访问。