Home
Map
String isEmptyUse the isEmpty method to test for zero-length strings. Test characters.count.
Swift
This page was last reviewed on Aug 21, 2023.
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.
Optional
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.
Property
Tip To see if a string is not empty, we use the exclamation mark to negate the result of isEmpty in an if-statement.
if
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.
String Length
// 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 21, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.