Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
dictionary
empty
communitycreator

How to check if a dictionary is empty in Swift

Theodore Kelechukwu Onyejiaku

Overview

The isEmpty property of a Dictionary instance allows us to see whether a dictionary is empty or not. An empty dictionary contains no key-value pairs.

Syntax

dictionary.isEmpty

Parameters

This function does not take any parameters.

Return values

The value returned is a Boolean. If it is empty, a true is returned, otherwise a false is returned.

Code example

// create dictionaries
var dict1 : [String: String] = [:]
var dict2 = [
  "name": "Theodore", 
  "role": "Developer"
]

// check if empty
print(type(of : dict1), dict1.isEmpty)
print(type(of : dict2), dict2.isEmpty)
Checking whether a dictionary is empty or not

Code explanation

  • Lines 2 and 3: We create two dictionaries, dict1 and dict2.
  • Lines 9 and 10: We check what type of instance the dictionaries are. If they’re empty, we print the results returned.

RELATED TAGS

swift
dictionary
empty
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring