gpt4 book ai didi

swift - 比较值并在 Swift 中返回一个 bool

转载 作者:搜寻专家 更新时间:2023-11-01 07:34:23 26 4
gpt4 key购买 nike

我正在将我的代码从 Objective-C 转换为 Swift。我声明了一个函数来比较两个属性的值并返回一个 Bool。我对为什么这段代码在 Swift 中不起作用感到困惑。

private var currentLineRange: NSRange?
var location: UInt?

func atBeginningOfLine() -> Bool {
return self.location! == self.currentLineRange?.location ? true : false
}

编译器报错:

Could not find an overload for == that accepts the supplied arguments

谢谢。

最佳答案

你有两个可选值,你想检查它们是否相等。有一个版本的 == 用于比较两个可选值——但它们必须是同一类型。

这里的主要问题是您正在比较NSRange.location,它是一个Int,与location,它是一个UInt。如果你试图在没有复杂的 optional 的情况下这样做,你会得到一个错误:

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 由于某些其他原因确实需要成为 UIntmap 可选项之一到其他比较它们:

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
}

关于swift - 比较值并在 Swift 中返回一个 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30836565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com