比较 Swift 中的两个双打:"Type of expression is ambiguous without more context"

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

我有一个函数必须检查一个值 (realOperand) 是否大于其他值 (realValue)。这些值是数字,但它们以字符串形式出现,我将它们解析为 Double:

return Double(realOperand) > Double(realValue)

我不明白为什么,但那一行给出了这个错误:

Type of expression is ambiguous without more context

函数

Double.init(_ string: String) returns 可选(类型 Double?)。

就像你这样写代码:

var a: Double? = nil
var b: Double? = 7

if a > b {
    print("A is greater")
}

nil 是大于还是小于 7?它是未定义的。 Optional 不是 Comparable

如果一个或两个字符串无法转换为 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

您可以重写比较运算符。可选值。

中的详细说明,您无法比较可选值。

func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
    if let lhs = lhs, let rhs = rhs {
        return lhs > rhs
    } else {
        return false
    }
}