你有两个可选值,你想检查它们是否相等。有一个 == 版本用于比较两个选项 - 但它们必须是相同的类型。
这里的主要问题是您将NSRange.location(即Int)与location(即UInt)进行比较。如果你尝试在没有复杂的可选选项的情况下这样做,你会得到一个错误:
let ui: UInt = 1
let i: Int = 1
// error: binary operator '==' cannot be applied to operands of
// type 'Int' and ‘UInt'
i == ui
有两种方法可以选择。将location 更改为Int,您将能够使用可选的==:
private var currentLineRange: NSRange?
var location: Int?
func atBeginningOfLine() -> Bool {
// both optionals contain Int, so you can use == on them:
return location == currentLineRange?.location
}
或者,如果 location 出于其他原因确实需要成为 UInt,则将 map 选项之一与另一个类型进行比较:
private var currentLineRange: NSRange?
var location: UInt?
func atBeginningOfLine() -> Bool {
return location.map { Int($0) } == currentLineRange?.location
}
有一点需要注意——nil 等于 nil。所以如果你不想要这个(取决于你想要的逻辑),你需要明确地为它编写代码:
func atBeginningOfLine() -> Bool {
if let location = location, currentLineRange = currentLineRange {
// assuming you want to stick with the UInt
return Int(location) == currentLineRange.location
}
return false // if either or both are nil
}