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条回答
SAY GOODBYE
2楼-- · 2020-01-27 00:51

I can recommend add small extension to String or Array that looks like

extension Collection {
    public var isNotEmpty: Bool {
        return !self.isEmpty
    }
}

With it you can write code that is easier to read. Compare this two lines

if !someObject.someParam.someSubParam.someString.isEmpty {}

and

if someObject.someParam.someSubParam.someString.isNotEmpty {}

It is easy to miss ! sign in the beginning of fist line.

查看更多
欢心
3楼-- · 2020-01-27 00:56

Check check for only spaces and newlines characters in text

extension String
{
    var  isBlank:Bool {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
    }
}

using

if text.isBlank
{
  //text is blank do smth
}
查看更多
做个烂人
4楼-- · 2020-01-27 01:05

You can also use an optional extension so you don't have to worry about unwrapping or using == 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
        }
    }
}

Note: when calling this on an optional, make sure not to use ? or else it will still require unwrapping.

查看更多
淡お忘
5楼-- · 2020-01-27 01:07

isEmpty will do as you think it will, if string == "", it'll return true. Some of the other answers point to a situation where you have an optional string.

PLEASE use Optional Chaining!!!!

If the string is not nil, isEmpty will be used, otherwise it will not.

Below, the optionalString will NOT be set because the string is nil

let optionalString: String? = nil
if optionalString?.isEmpty == true {
     optionalString = "Lorem ipsum dolor sit amet"
}

Obviously you wouldn't use the above code. The gains come from JSON parsing or other such situations where you either have a value or not. This guarantees code will be run if there is a value.

查看更多
劫难
6楼-- · 2020-01-27 01:08

I am completely rewriting my answer (again). This time it is because I have become a fan of the guard statement and early return. It makes for much cleaner code.

Non-Optional String

Check for zero length.

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)

If the if statement passes, then you can safely use the string knowing that it isn't empty. If it is empty then the function will return early and nothing after it matters.

Optional String

Check for nil or zero length.

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)

This unwraps the optional and checks that it isn't empty at the same time. After passing the guard statement, you can safely use your unwrapped nonempty string.

查看更多
姐就是有狂的资本
7楼-- · 2020-01-27 01:08

In Xcode 10.2 swift 5

Use

var isEmpty: Bool { get } 

Example

let lang = "Swift 5"

if lang.isEmpty {
   print("Empty string")
}

If you want to ignore white spaces

if lang.trimmingCharacters(in: .whitespaces).isEmpty {
   print("Empty string")
}
查看更多
登录 后发表回答