How to get the first key-value pair of a Swift dictionary

Overview

The first property, when used on a dictionary instance, returns the first key-value pair of the dictionary.

Syntax

dictionary.first

Return value

The first entry of a dictionary in a key-value pair is returned.

Code example

// Create a dictionary
var months = [
"1" : "One",
"2" : "Two",
"3" : "Three",
"4" : "Four",
"5" : "Five",
"6" : "Six",
"7" : "Seven",
"8" : "Eight",
"9" : "Nine"
]
// Display dictionary
print(months)
// Get first entry
print(months.first!)

Explanation

  • Line 2: We create a dictionary instance called months.
  • Line 18: We fetch the first entry of the dictionary using the first property, then print it to the console.

Free Resources