Khaled Annajar - 1 year ago 38

Swift Question

In this code in play ground I git error "Ambiguous use of 'tan'"

`let mytan = tan(2)`

Why is this not working?

Answer Source

You have already found a solution, but as your question was

Why is this not working?

I'll try to add an explanation for the problem.

Like most mathematical functions, `tan()`

is overloaded for the various
floating point types:

```
public func tan(x: Float) -> Float
public func tan(_: Double) -> Double
public func tan(x: CGFloat) -> CGFloat
```

All these floating point types conform to the `IntegerLiteralConvertible`

protocol, which means that `2`

can be interpreted as a
`Float`

, `Double`

, or `CGFloat`

. Therefore, in

```
let mytan = tan(2)
```

the compiler cannot decide which one to use:

error: ambiguous use of 'tan' let mytan = tan(2) ^ Darwin.tan:2:13: note: found this candidate public func tan(x: Float) -> Float ^ Darwin.tan:1:13: note: found this candidate public func tan(_: Double) -> Double ^ CoreGraphics.tan:2:13: note: found this candidate public func tan(x: CGFloat) -> CGFloat

On the other hand, a floating point literal like `2.0`

is by default
interpreted as a `Double`

, and that is why

```
let mytan = tan(2.0)
```

compiles.