在Objective C中,可以执行以下操作来检查字符串:
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}
Run Code Online (Sandbox Code Playgroud)
如何在Swift中检测空字符串?
chr*_*lee 225
现在有内置的能力来检测空字符串.isEmpty:
if emptyString.isEmpty {
print("Nothing to see here")
}
Run Code Online (Sandbox Code Playgroud)
Apple预发布文档:"字符串和字符".
Alb*_*ori 98
检查字符串是否为空的简明方法是:
var myString: String? = nil
if (myString ?? "").isEmpty {
print("String is nil or empty")
}
Run Code Online (Sandbox Code Playgroud)
Sur*_*gch 48
我完全重写了我的答案(再次).这一次是因为我已成为guard声明和早期回归的粉丝.它使代码更清晰.
检查零长度.
let myString: String = ""
if myString.isEmpty {
print("String is empty.")
return // or break, continue, throw
}
// myString is not empty (if this point is reached)
print(myString)
Run Code Online (Sandbox Code Playgroud)
如果if语句通过,那么您可以安全地使用该字符串,因为它知道它不是空的.如果它是空的,那么函数将提前返回,并且在它重要之后不会发生任何事
检查零或零长度.
let myOptionalString: String? = nil
guard let myString = myOptionalString, !myString.isEmpty else {
print("String is nil or empty.")
return // or break, continue, throw
}
// myString is neither nil nor empty (if this point is reached)
print(myString)
Run Code Online (Sandbox Code Playgroud)
这将打开可选项,并检查它是否同时为空.传递guard语句后,您可以安全地使用您的unwrapped非空字符串.
Sar*_*ith 32
使用
var isEmpty: Bool { get }
Run Code Online (Sandbox Code Playgroud)
例
let lang = "Swift 5"
if lang.isEmpty {
print("Empty string")
}
Run Code Online (Sandbox Code Playgroud)
Evg*_*nii 27
这是我检查字符串是否为空的方法.'blank'是指一个空的字符串,或者只包含空格/换行符.
struct MyString {
static func blank(text: String) -> Bool {
let trimmed = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return trimmed.isEmpty
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用:
MyString.blank(" ") // true
Run Code Online (Sandbox Code Playgroud)
Joh*_*ery 14
您还可以使用可选扩展,这样您就不必担心展开或使用== true:
extension String {
var isBlank: Bool {
return self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
extension Optional where Wrapped == String {
var isBlank: Bool {
if let unwrapped = self {
return unwrapped.isBlank
} else {
return true
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:在可选项上调用此项时,请确保不要使用?,否则仍需要解包.
要同时执行nil检查和长度,你可以使用Swift 2.0和iOS 9
if(yourString?.characters.count > 0){}
Run Code Online (Sandbox Code Playgroud)
isEmpty 会按照你的想法做,如果 string == "",它将返回 true。其他一些答案指出了您有可选字符串的情况。
请使用可选链接!!!!
如果字符串不为nil,则会使用isEmpty,否则不会。
下面,可选字符串不会被设置,因为字符串为零
let optionalString: String? = nil
if optionalString?.isEmpty == true {
optionalString = "Lorem ipsum dolor sit amet"
}
Run Code Online (Sandbox Code Playgroud)
显然你不会使用上面的代码。收益来自 JSON 解析或其他此类情况,其中您要么有值,要么没有值。这保证了如果有值,代码就会运行。