gpt4 book ai didi

swift - 使用 "if"条件检查多个字符串是否为空或 nil

转载 作者:搜寻专家 更新时间:2023-10-31 22:15:32 25 4
gpt4 key购买 nike

在 Swift if 语句中链接多个条件的正确语法是什么,如下所示:

if (string1!=nil && string2!=nil) {}

或:

if (string1.isEmpty && string2.isEmpty) {}

最佳答案

没有必要围绕这两个条件使用():

let name1 = "Jim"
let name2 = "Jules"

if name1.isEmpty && name2.isEmpty {
println("Both strings where empty")
}

此外,检查字符串是否为 nil 与检查字符串是否为空不同。

为了检查您的字符串是否为 nil,它们首先必须是 Optionals。

var name1: String? = "Jim"
var name2: String? = "Jules"

if name1 != nil && name2 != nil {
println("Strings are not nil")
}

安全解包:

if let firstName = name1, secondName = name2 {
println("\(firstName) and \(secondName) are not nil")
}

在这种情况下,两个字符串都不是 nil 但仍可能为空,因此您也可以检查一下:

if let firstName = name1, secondName = name2 where !firstName.isEmpty && !secondName.isEmpty {
println("\(firstName) and \(secondName) are not nil and not empty either")
}

关于swift - 使用 "if"条件检查多个字符串是否为空或 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682310/

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