Check empty string in Swift?

2020-01-27 00:23发布

In Objective C, one could do the following to check for strings:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}

How does one detect empty strings in Swift?

标签: swift
13条回答
Explosion°爆炸
2楼-- · 2020-01-27 00:45

There is now the built in ability to detect empty string with .isEmpty:

if emptyString.isEmpty {
    print("Nothing to see here")
}

Apple Pre-release documentation: "Strings and Characters".

查看更多
别忘想泡老子
3楼-- · 2020-01-27 00:47

Here is how I check if string is blank. By 'blank' I mean a string that is either empty or contains only space/newline characters.

struct MyString {
  static func blank(text: String) -> Bool {
    let trimmed = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    return trimmed.isEmpty
  }
}

How to use:

MyString.blank(" ") // true
查看更多
▲ chillily
4楼-- · 2020-01-27 00:47

To do the nil check and length simultaneously Swift 2.0 and iOS 9 onwards you could use

if(yourString?.characters.count > 0){}
查看更多
【Aperson】
5楼-- · 2020-01-27 00:48

What about

if let notEmptyString = optionalString where !notEmptyString.isEmpty {
    // do something with emptyString 
    NSLog("Non-empty string is %@", notEmptyString)
} else {
    // empty or nil string
    NSLog("Empty or nil string")
}
查看更多
ら.Afraid
6楼-- · 2020-01-27 00:49
if myString?.startIndex != myString?.endIndex {}
查看更多
Fickle 薄情
7楼-- · 2020-01-27 00:50

For optional Strings how about:

if let string = string where !string.isEmpty
{
    print(string)
}
查看更多
登录 后发表回答