swift - 根据其元素的类型重载 Array 函数

标签 swift

是否可以在 Swift 中实现类似的功能?

extension Array {
    func processItems<Element: Protocol1>() { 
        for item in self {
            // deal with Protocol1 objects
        }
    }

    func processItems<Element: Protocol2>() {
        for item in self {
            // deal with Protocol2 objects
        }
    }
}

我想要实现的是扩展 Array 并根据数组中元素的类型重载 processItems

另一种方法是要么拥有一个函数,要么使用可选的强制转换/绑定(bind),但是我会以这种方式失去类型安全,并且最终可能会得到一个包含很多 if if-let< 的庞大函数

func processItem() {
    for item in self {
        if let item = item as? Protocol1 {
            // deal with Protocol1 objects
        } else if let item = item as? Protocol2 {
            // deal with Protocol2 objects
        }
    }
},

或将 processItems 声明为自由函数:

func processItems<T: Protocol1>(items: [T]) {
    // ...
}

func processItems<T: Protocol2>(items: [T]) {
    // ...
}

但是我想知道我是否可以将该函数“嵌入”到 Array 类中,以使其保持本地化。如果这是可能的,那么该技术可以应用于其他泛型类(内置或自定义)。

最佳答案

这个怎么样?

extension Array where Element: Protocol1 {
    func processItems() {
        for item in self {  // item conforms to Protocol1
            ...

关于swift - 根据其元素的类型重载 Array 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34671396/

相关文章:

Swift 错误初始化嵌入类型的数组/字典

swift - AKSwiftSlideMenu 添加更多 View Controller

swift - Swift 中 String 的 4 位哈希

ios - 在协议(protocol)方法的参数中使用默认值时出错

xcode - SourceKitService 吸取内存并停止所有进程

json - NSCoding 和 Codable 属性 <=> JSON 格式 <=>(读/写)文件

ios - Swift iframe 未在 Web View 中加载

ios - 如何在集合单元格中重绘动态大小的 UIView

ios - 如何以编程方式从 Storyboard 中填充静态 UITableView?

json - 如何制作一个快速的 Codable 结构,它将在 JSON 中解码和编码 MongoDB _id ObjectId()