Swift Dictionary first

The first property returns the first key/value pair of the dictionary.

Example

var languages = ["Swift": 2012, "C": 1972, "Java": 1995]

// return total elements of languages var result = languages.first
print(result) // Output: (key: "Swift", value: 2012)

first Syntax

The syntax of the dictionary first property is:

dictionary.first 

Here, dictionary is an object of the Dictionary class.


first Return Values

The first property returns the first key/value present in the dictionary.

Note: The first property returns an optional value, so we need to unwrap it. There are different techniques to unwrap optionals. To learn more about optionals, visit Swift Optionals.


Example: Swift Dictionary first

var nameAge = ["Alcaraz": 18, "Sinner": 20, "Nadal": 34]

// first key/value pair of nameAge print(nameAge.first!)
var employees = ["Saby": 1994]
// return first key/value pair of employees print(employees.first!)

Output

(key: "Alcaraz", value: 18)
(key: "Saby", value: 1994)

In the above example, we have created two dictionaries named nameAge and employees with 3 and 1 key/value pairs respectively.

Here, we have used the first property to return the first key/value pair from nameAge and employees respectively.

Did you find this article helpful?