How can we check if a string is empty in Swift

Overview

In Swift, we can use the isEmpty property to check if a string is empty or not.

Syntax

string.isEmpty

Return value

The value returned is a Boolean value, which indicates whether the string is empty or has characters in it.

Code example

// create strings
let str1 = "Edpresso"
let str2 = "is"
let str3 = "awesome!"
let str4 = ""
// check if empty and print result
print(str1.isEmpty)
print(str2.isEmpty)
print(str3.isEmpty)
print(str4.isEmpty)

Code explanation

  • Lines 2–5: We create some strings.
  • Lines 8–11: We check the strings to see if they are empty or not, using the isEmpty property. Then, we print the results to the console.

Free Resources