Yuchuan Max Chen
Yuchuan Max Chen

Reputation: 1

On Swift: Met error about parentheses type writing sqrt

I wrote the following code:

var number3 = sqrt(9)

and the System reports error saying that

Variable number3 inferred to have type "()", which may be unexpected."

How can this error be? I found another user saying that (9) refers to (int) type instead of int type. But the sqrt function need an parentheses. How do you guys deal with this problem?

Upvotes: 0

Views: 228

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

There error here is incorrect (and fixed in the latest versions of Swift). The correct error is:

  1> import Darwin
  2> var number3 = sqrt(9)
repl.swift:2:15: error: ambiguous use of 'sqrt'
var number3 = sqrt(9)
              ^
Darwin.sqrt:1:6: note: found this candidate
func sqrt(x: Float) -> Float
     ^
Darwin.sqrt:1:6: note: found this candidate
func sqrt(_: Double) -> Double
     ^

The problem is that Swift doesn't know if you want to convert the literal "3" into a Float or a Double. Rather than force it to do that, just use a Double directly:

  2> sqrt(9.0)
$R0: Double = 3

Upvotes: 2

Related Questions