How to check if a set is empty in Swift
Overview
A set stores unique values or elements as a collection in Swift. An empty set has no value in it. The isEmpty method determines if a set is empty. It returns a Boolean.
Syntax
set.isEmpty
Syntax to check if a set is empty
Parameters
There are no parameters.
Return value
The returning value of isEmpty is Boolean. If the set is empty, true is returned. Otherwise, false is returned.
Example
// create some setslet evenNumbers : Set = [2, 4, 6, 8, 10]let oddNumbers : Set = [3, 5, 7, 9, 11]let emptySet = Set<String>()// check if emptyprint(evenNumbers.isEmpty) // falseprint(oddNumbers.isEmpty) // falseprint(emptySet.isEmpty) // true
Explanation
- Lines 2 and 3: We create some sets and give them some values.
- Line 4: We create an empty set.
- Lines 7–9: We use the
isEmptymethod to check if the sets we create are empty. The results are printed to the console.