C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: To see if a string is not empty, we use the exclamation mark to negate the result of isEmpty in an if-statement.
Swift program that uses empty string, isEmpty
var example = String()
// The string is currently empty.
if example.isEmpty {
print("No characters in string")
}
// Now isEmpty will return false.
example = "frog"
if !example.isEmpty {
print("Not empty now")
}
Output
No characters in string
Not empty now
So: We can use characters.count instead of the isEmpty property on strings to test for emptiness.
Swift program that uses characters.count, isEmpty
// Test the characters count and isEmpty.
print("::ON EMPTY STRING::")
var example = String()
print(example.characters.count)
print(example.isEmpty)
print("::ON 1-CHAR STRING::")
example = "x"
print(example.characters.count)
print(example.isEmpty)
Output
::ON EMPTY STRING::
0
true
::ON 1-CHAR STRING::
1
false