数组的通用扩展不起作用

时间:2017-03-09 22:44:53

标签: swift generics swift-extensions

我一直在使用Generics和Extensions来处理Swift 3中的现有类型。我编写了两个通用的Array函数,它们使用find-and-replace方法扩展Array,名为replacement()和replace()。 replacement()函数按预期工作,但replace()函数有编译时错误。这是代码和其中一种方法的测试。

extension Array {
    func replaced<T: Equatable>(each valueToReplace: T, with newValue: T) -> [T] {
        var newArray:[T] = []
        for index:Int in 0..<self.count {
            if let temp = self[index] as? T, temp == valueToReplace{
                newArray.append(newValue)
            }else{
                newArray.append(self[index] as! T)
            }
        }
        return newArray
    }
    mutating func replace<T: Equatable>(each valueToReplace: T, with newValue: T) {
        for index:Int in 0..<self.count {
            if let temp = self[index] as? T, temp == valueToReplace {
                // FIXME: self[index] = newValue 
            }
        }
        return
    }
}
var j = [1,2,3,4,3,6,3,8,9]
var newArray = j.replaced(each: 3, with: 0)

我在使用“// FIXME:”注释注释掉的第二个方法replace()上遇到编译时错误。编译时错误表示“对成员'下标'的模糊引用”。

如何修复replace()代码以使其有效?

1 个答案:

答案 0 :(得分:1)

试一试

extension Array where Element: Equatable {
    func replaced (each valueToReplace: Element, with newValue: Element) -> [Element] {
        var newArray = [Element]()
        newArray.reserveCapacity(self.count)

        for element in self {
            let newElement = (element == valueToReplace) ? newValue : element
            newArray.append(newElement) 
        }

        return newArray
    }

    mutating func replace(each valueToReplace: Element, with newValue: Element) {
        for (i, element) in self.enumerated() {
            if element == valueToReplace { self[i] = newValue }
        }
    }
}

var j = [1,2,3,4,3,6,3,8,9]
var newArray = j.replaced(each: 3, with: 0)

最好只需将replaced委托给replace即可删除冗余:

extension Array where Element: Equatable {
    func replaced(each valueToReplace: Element, with newValue: Element) -> [Element] {
        var copy = self
        copy.replace(each: valueToReplace, with: newValue)
        return copy
    }

    mutating func replace(each valueToReplace: Element, with newValue: Element) {
        for (i, element) in self.enumerated() {
            if element == valueToReplace { self[i] = newValue }
        }
    }
}