根据数组元素的类型重载数组函数



有可能在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

另一种选择是要么有一个单一的函数,要么使用可选的强制转换/绑定,但我会以这种方式放松类型安全性,如果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
            ...

最新更新