Site icon CodeWithSwift

Dictionary

A dictionary in Swift is a collection type that stores key-value pairs. Each key is unique and you use it to access its corresponding value.

dictionary[key] = value
var scores: [String: Int] = [
    "Bishal": 1,
    "Swift": 2,
    "iOS": 3
]

// Access a value
if let score = scores["Bishal"] {
    print("Bishal's score: \(score)")
}

//OutPut
Bishal's score: 1

// Add a new key-value pair
scores["Ram"] = 10

// Update a value
scores["Swift"] = 92

// Remove a key-value pair
scores["iOS"] = nil

print(scores)

//OutPut 
["Xcode": 1, "Swift": 92, "Ram": 10]

Iterating Over a Dictionary

var countries: [String: Int] = [ "USA": 1, "India": 2]

// Iterate over key-value pairs
for (key, value) in countries {
    print("\(key): \(value)")
}

// Output
[USA: 1, India: 2]


//Iterate Over Keys Only

for key in countries.keys {
    print("Key: \(key)")
}

// Output

Key: USA
Key: India

//Iterate Over Values Only

for value in countries.values {
    print("Value: \(value)")
}


Output:

Value: 1
Value: 2
Exit mobile version