gpt4 book ai didi

arrays - 数组的变异扩展

转载 作者:搜寻专家 更新时间:2023-11-01 07:18:31 27 4
gpt4 key购买 nike

我正在尝试创建一个扩展,但不知何故它一直在说:

Ambiguous reference to member '=='.

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
}

我做错了什么?

最佳答案

试试这个:

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 需要是 Array 的 Element,可以是 Array 的任何子类Foo.

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

(为了测试上面的代码,我从你的 Foo 中删除了 : Equatable,当你使用 index(where:)在扩展中。)

关于arrays - 数组的变异扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com