Array的变异扩展

时间:2016-11-06 05:58:48

标签: arrays swift

我试图创建一个扩展程序但不知何故它一直在说:

  

对成员的歧义提及' =='。

class Foo: Equatable {
    var string = ""
    var number = 0

    init(string: String, number: Int) {
        self.string = string
        self.number = number
    }
}

extension Array where Iterator.Element: Foo {

    mutating func replace(object: Foo) {
        if let index = index(where: { $0.number == object.number}) {
            self[index] = object
        }
    }
}

func ==(lhs: Foo, rhs: Foo) -> Bool {
    return lhs.number == rhs.number
}

我做错了什么?

2 个答案:

答案 0 :(得分:2)

试试这个:

extension Array where Element: Foo {

    mutating func replace(object: Element) {
        if let index = index(where: {$0.number == object.number}) {
            self[index] = object
        }
    }

}

要使self[index] = object有效,object必须是数组的Element,可以是Foo的任何子类。

不幸的是,Swift无法从约束推断Element的类型Iterator.Element。您可能需要直接将约束声明为Element

(为了测试上面的代码,我已从您的: Equatable中删除了Foo,这在您在扩展程序中使用index(where:)时无关紧要。)

答案 1 :(得分:0)

Swift 5版本并支持多对象替换(如果不存在则添加)。

extension Foo {
    public static func == (lhs: Object, rhs: Object) -> Bool {
        return lhs.id == rhs.id
    }
}

extension Array where Element: Foo {
    mutating func replace(object: Element) -> Bool {
        if let index = firstIndex(where: {$0 == object}) {
            self[index] = object
            return true
        }
        return false
    }

    mutating func replace(objects: Array<Element>) {
        objects.forEach { (object) in
            if replace(object: object) == false {
                self.append(object)
            }
        }
    }
}