在 Swift 中将 IF LET 与 OR 组合在一起



有没有一种优雅的方法将两个 if let 语句组合在一起 or 运算符。例如,我需要检查字符串"pass"、"true"或整数 1。下面的函数就是这样做的...

func test(content: Any) -> String {
if let stringValue = (content as? String)?.lowercased(),
["pass", "true"].contains(stringValue) {
return "You Passed"
}
if let numValue = (content as? Int),
1 == numValue {
return "YOU PASSED"
}
return "You Failed"
}
test(content: "Pass") //"You Passed"
test(content: 1) //"YOU PASSED"

将这两个 if let 语句结合起来来处理传入的数据的最简单方法是什么?

如果 let带有 or inside ,则不能执行,因为如果由于一个条件而进入语句内部,则另一个条件可以为 nil,而使用 if let 可以确保语句内的 var 不是 nil。

我只是检查它们是否不是零并做点什么。

即使在此示例中,您也不需要使用 if lets。(我用一个来展示如何使用 AND 运算符,使用 OR 是不可能的。

if let stringValue = (content as? String)?.lowercased(), (["pass", "true"].contains(stringValue) || 1 == (numValue ?? 0)) {
return "You Passed"
}

此外,如果您只想检查变量的值是否为 nil,则根据 SwiftLint 的说法,最好使用 != nil 而不是 if let。

您可能只是内联所有内容:

func test(content: Any) -> String {
if ["pass", "true"].contains((content as? String)?.lowercased())
|| (content as? Int) == 1 {
return "You Passed"
}
return "You Failed"
}

但总的来说,我建议将这些东西分成多种方法,一种用于检查值,另一种用于将其转换为String

func test(content: Any) -> Bool {
return ["pass", "true"].contains((content as? String)?.lowercased())
|| (content as? Int) == 1
}
func testToString(content: Any) -> String {
return test(content: content) ? "You passed" : "You failed"
}

您也可以先将所有值转换为String,然后检查:

func test(content: Any) -> Bool {
let stringValue = String(describing: content).lowercased()
return ["1", "pass", "true"].contains(stringValue)
}

但是,这会增加一些误报,因为即使对于字符串,它也会返回true"1"我通常建议不要这样做。

有类似的问题,并希望将两个let try?赋值组合起来,以通过代码 DRY 保存。让它工作,但需要确保括号正确:

if let number = try? ((try? Number.parse("1")) ?? Number.parse("2")) {
print("Yay, a number: (number)")
} else {
print("Nope, not a number")
}
// => Prints "Yay, a number: 1"
if let number = try? ((try? Number.parse("a")) ?? Number.parse("2")) {
print("Yay, a number: (number)")
} else {
print("Nope, not a number")
}
// => Prints "Yay, a number: 2"

我在这个例子中模拟了以下内容,在实际代码中,我使用 PhoneNumberKit 解析了一个数字。

struct Number {
static func parse(_ numberString: String) throws -> Int {
if let result = Int(numberString) {
return result
} else {
throw ParsingError.notANumber
}
}
enum ParsingError: Error {
case notANumber
}
}

显然,当我回答这个问题时,我分心了,没有仔细阅读。不,您编写一个包含 2 个可选绑定if let语句的表达式,其中只有一个为真。

你不能说

如果设 x = y 设 a = b

似乎最干净的方法是使用 else:

if let x = y { code }
else if let a = b { other code } 

以前的答案没有回答提出的问题:

是的,您可以组合多个 if let 语句:

var x: Int? = 1
var y: String? = ""
var z = 2
if let x = x,
let y = y,
z == 2 {
//do stuff
}

上面的 if 块只有在 x 和 y 不为 nil 时才执行(和 z == 2(

更好的是,每个后续if let可选绑定都可以使用与上一个if let一起解包的可选绑定。

最新更新