Search code examples
iosswiftdouble

Comparing two Doubles in Swift: "Type of expression is ambiguous without more context"


I have a function that must check if a value (realOperand) is bigger than other value (realValue). These values are numeric, but they come in string, and I parse them to Double:

return Double(realOperand) > Double(realValue)

I can't understand why, but that line is giving this error:

Type of expression is ambiguous without more context


Solution

  • The function

    Double.init(_ string: String) returns an Optional (Type Double?).

    It would be like you wrote this code:

    var a: Double? = nil
    var b: Double? = 7
    
    if a > b {
        print("A is greater")
    }
    

    Is nil greater than or less than 7? It's undefined. Optionals are not Comparable.

    You need to decide what to do if either or both strings can't be converted to Double:

    guard let operand = Double(realOperand),
      value = Double(realValue) else {
        // Crash on purpose. Not a great option for user-entered Strings!
        fatalError("Could not convert strings to Doubles")
    }
    
    return operand > value