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

标签 swift

在 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/

相关文章:

Swift UIImagePickerController didFinishPickingMediaWithInfo 未触发

Swift - cellForItemAtIndexPath 在调整图像大小时展开可选值

swift - Swift 数组中的段错误?

ios - 如何在iOS中获取默认的系统颜色?

ios - 如何在 Skype 上共享文本

swift - 在 Swift 中查找字典条目的索引

ios - 如何通过swift使用TextField添加 subview TagView编程?

ios - 如何随着时间的推移永久保存文本行

swift - 引用另一个 func 中的 func (swift)

ios - 如何在AppDelegate中隐藏和显示UIViewController按钮? - swift