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?
I can recommend add small extension to String or Array that looks like
With it you can write code that is easier to read. Compare this two lines
and
It is easy to miss ! sign in the beginning of fist line.
Check check for only spaces and newlines characters in text
using
You can also use an optional extension so you don't have to worry about unwrapping or using
== true
:Note: when calling this on an optional, make sure not to use
?
or else it will still require unwrapping.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
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.
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.
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.
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.In Xcode 10.2 swift 5
Use
Example
If you want to ignore white spaces