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.
Optional note. 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.
First example. 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.
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.
So We can use count instead of the 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
Summary. 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."
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 21, 2023 (edit).