数组的通用扩展不起作用

Generic Extension to Array Not Working

我一直在研究 Swift 中现有类型的泛型和扩展 3. 我编写了两个通用数组函数,它们使用查找和替换方法扩展数组,名为 replaced() 和 replace( ). replaced() 函数按预期工作,但 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)

我在第二种方法 replace() 上遇到编译时错误,该错误位于用“//FIXME:”注释注释掉的行。编译时错误显示,"Ambiguous reference to member 'subscript'"。

如何修复 replace() 代码使其正常工作?

试一试

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 }
        }
    }
}