Jofkos - 22 days ago 6

Swift Question

It is probably so simple, but for a reason swift doesn't like my implementation of the + operator...

I've got a simple number protocol:

`protocol Number : CustomStringConvertible {`

var doubleValue: Double { get }

}

A simple implementation of the same:

`struct SimpleNumber : Number {`

let doubleValue: Double

let description: String

init(_ double: Double) {

doubleValue = double

description = "\(double)"

}

}

and an extension for the operator overloading:

`extension Number {`

static func + (lhs: Number, rhs: Number) -> Number {

return SimpleNumber(lhs.doubleValue + rhs.doubleValue)

}

}

So far, so good. But now, when I try to use that operator:

`let number1: Number = SimpleNumber(1)`

let number2: Number = SimpleNumber(2)

let number3: Number = number1 + number2;

Xcode tells me, that the operator is ambiguous.

So, why? My definition is the only one that fit's for two

`Number`

What am I doing wrong?

Answer

The `+`

operator shouldn't be inside the extension, but rather a global `func`

. Replace your definition of `+`

:

```
extension Number {
static func + (lhs: Number, rhs: Number) -> Number {
return SimpleNumber(lhs.doubleValue + rhs.doubleValue)
}
}
```

with simply

```
func + (lhs: Number, rhs: Number) -> Number {
return SimpleNumber(lhs.doubleValue + rhs.doubleValue)
}
```

and it will work. I guess what you have done is created a static function `Number.+`

, not the global function `+`

that you are using...

Source (Stackoverflow)

Comments