How to iterate over a dictionary in Swift

5 Answers

0 votes
import Foundation

let myDictionary = ["key1": "value1", "key2": "value2", "key3": "value3"]

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

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




/*
run:  

Key: key2
Key: key3
Key: key1
Value: value2
Value: value3
Value: value1
 
*/

 



answered Dec 14, 2024 by avibootz
0 votes
import Foundation

let myDictionary = ["key1": "value1", "key2": "value2", "key3": "value3"]

for (key, value) in myDictionary {
    print("\(key): \(value)")
}



/*
run:  
 
key2: value2
key3: value3
key1: value1
 
*/

 



answered Dec 14, 2024 by avibootz
0 votes
import Foundation

let myDictionary = ["key1": "value1", "key2": "value2", "key3": "value3"]

myDictionary.forEach { key, value in
    print("\(key): \(value)")
}



/*
run:  
 
key1: value1
key2: value2
key3: value3
 
*/

 



answered Dec 14, 2024 by avibootz
0 votes
import Foundation

let myDictionary = ["key1": "value1", "key2": "value2", "key3": "value3"]

myDictionary.forEach { (key, value) in
    print("Key: \(key), Value: \(value)")
}



/*
run:
     
Key: key2, Value: value2
Key: key3, Value: value3
Key: key1, Value: value1
     
*/
 

 



answered Mar 3, 2025 by avibootz
0 votes
import Foundation

let myDictionary = ["key1": "value1", "key2": "value2", "key3": "value3"]

// Iterating over keys
for key in myDictionary.keys {
    print("Key: \(key)")
}

// Iterating over values
for value in myDictionary.values {
    print("Value: \(value)")
}



/*
run:
     
Key: key3
Key: key1
Key: key2
Value: value3
Value: value1
Value: value2
     
*/
 

 



answered Mar 3, 2025 by avibootz
...