Henny Lee Henny Lee - 1 year ago 107
Swift Question

Mutating extension for Array

I'm trying to create an extension but somehow it keeps saying:

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

What am I doing wrong?

Answer Source

Try this:

extension Array where Element: Foo {

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


To make self[index] = object valid, object needs to be an Element of the Array, which can be any subclass of Foo.

And unfortunately, Swift cannot infer the type of Element from the constraint to Iterator.Element. You may need to declare the constraint to Element directly.

(And to test the code above, I have removed : Equatable from your Foo, which is irrelevant when you use index(where:) in the extension.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download