Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
set
isempty
communitycreator

How to check if a set is empty in Swift

Theodore Kelechukwu Onyejiaku

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 sets
let evenNumbers : Set = [2, 4, 6, 8, 10]
let oddNumbers : Set = [3, 5, 7, 9, 11]
let emptySet = Set<String>()

// check if empty
print(evenNumbers.isEmpty) // false
print(oddNumbers.isEmpty)  // false
print(emptySet.isEmpty)    // true
Check if a set is empty in Swift

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 isEmpty method to check if the sets we create are empty. The results are printed to the console.

RELATED TAGS

swift
set
isempty
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring