IsEmpty
A string
can have many characters. But a valid string
can also have zero characters—this is an empty string
. With the isEmpty
method we can test for empty strings.
Empty strings may sometimes occur in Swift programs. But sometimes instead of empty strings, we can use an Optional
String
. We can use "if let" then to access the string
safely.
To create an empty string
, we use the String()
initializer. We can test for an empty string
with isEmpty
. The isEmpty
property returns true or false.
string
is not empty, we use the exclamation mark to negate the result of isEmpty
in an if
-statement.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") }No characters in string Not empty now
Count
With the count property we get the count of characters in a string
—its length. An empty string
always has a length of 0.
isEmpty
property on strings to test for emptiness.// Test the character count and isEmpty. print("::ON EMPTY STRING::") var example = String() print(example.count) print(example.isEmpty) print("::ON 1-CHAR STRING::") example = "x" print(example.count) print(example.isEmpty)::ON EMPTY STRING:: 0 true ::ON 1-CHAR STRING:: 1 false
Methods can return a String
, but a String
cannot be nil
—only an Optional
string
can be nil
. So with empty strings (tested by isEmpty
) we can signify "no result."