- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swift Program to check the given string is empty or not
To check if the given string is empty or not Swift provides an inbuilt property named as isEmpty. This property will return true if the given string is empty. And return false if the given string is not empty. Here empty string means whose length is 0 or we can say a string that does not contain any character.
String 1 = “Swift” String 2 = “”
Where string 1 is not an empty string because it contains a sequence of characters or it has some length. Whereas string 2 is an empty string because it does contains anything or has a length of 0.
Syntax
Str.isEmpty
Where Str is the string to which we check if it is empty or not, using the isEmpty property.
Algorithm
Step 1 − Create a string.
Step 2 − Check if the given string is empty or not with the help of isEmpty property.
Step 3 − If the given string is empty, then print “String is empty”.
Step 4 − If the given string is not empty, then print “String is not empty”.
Example 1
In the following Swift program, we check if the given string is empty or not. So we will create a string, and then we will use the isEmpty property to check if the current string is empty or not. If the isEmpty property return true, then that means the current string is empty. Otherwise not.
import Foundation import Glibc let firstString = "Welcome to TutorialsPoint" if firstString.isEmpty { print("The string is empty") } else { print("The string is not empty") }
Output
The string is not empty
Example 2
As we know that an empty string is of zero length. So we can also check if the given string is empty or not using the count property. The count property returns the size of the string. So if the size of the string is 0, then that means the string is empty. Otherwise not.
import Foundation import Glibc let mString = "" if mString.count == 0 { print("The string is empty") } else { print("The string is not empty") }
Output
The string is empty
Conclusion
So this is how we can check if the given string is empty or not., Both the isEmpty and count methods will return the same return. But the most appropriate method to check if the string is empty or not is the isEmpty method.