Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dictionary
key-value pair
swift
communitycreator

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

Theodore Kelechukwu Onyejiaku

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!)
Getting the first entry of a dictionary in Swift

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.

RELATED TAGS

dictionary
key-value pair
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring