【问题标题】:Compare value and return a bool in Swift在 Swift 中比较值并返回一个布尔值
【发布时间】:2015-06-15 02:21:04
【问题描述】:

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

private var currentLineRange: NSRange?
var location: UInt?

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

编译器给了我一个错误:

找不到接受所提供参数的 == 重载

谢谢。

【问题讨论】:

  • 你为什么使用多余的? true : false? ? 左侧的值已经是Bool。直接退货吧。
  • @GregHewgill 哦,你是对的。

标签: swift boolean


【解决方案1】:

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

这里的主要问题是您将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
}

【讨论】:

    【解决方案2】:

    Swift 有运算符重载,所以 == 是一个函数。您必须定义一个接受您的两种类型的函数。

    如果你删除 UInt 它可以工作:

    class Document {
        private var currentLineRange: NSRange?
        var location: Int?
    
        func atBeginningOfLine() -> Bool {
            if let currentLocation = self.location, lineRange = self.currentLineRange {
                return currentLocation=lineRange?.location
            } else {
                return false
            }
        }
    }
    

    修改为 null 安全。

    【讨论】:

    • 如果两个值都为 nil,它将返回 true
    • func NSMakeRange(loc: Int, len: Int) -> NSRange 我应该看到这个len 是int 类型。 :)
    • @LeoDabus 我当然同意 if let 更好,但我试图回答这个问题而不是制作这个函数的最佳版本。
    • @Wongzigii 喜欢运算符重载,我自己也习惯了,很久以前 C++ 没用过!
    猜你喜欢
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多