Overload Array函数基于其元素的类型

时间:2016-01-08 07:14:12

标签: 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

另一种方法是使用单个函数并使用可选的强制转换/绑定,但是我以这种方式放松了类型的安全性,如果if-let可能最终会出现一个包含很多函数的庞大函数&#39; S

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]) {
    // ...
}

但是,我想知道我是否可以&#34;嵌入&#34;将函数放入Array类,以使其本地化。如果可以,那么该技术可以应用于其他泛型类(内置或自定义)。

1 个答案:

答案 0 :(得分:3)

这个怎么样?

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