NFC.cool
NFC.cool

Reputation: 3303

How to loop over a dictionary in Swift 5?

In Swift 4 I could the code below worked but in Swift 5 I get the following error: Type 'Dictionary<String, String>.Values.Iterator' does not conform to protocol 'Sequence'

guard let userIds = users.values.makeIterator() else { return }

for userId in userIds {
    // User setup
}

What is the right way in Swift 5 now?

Upvotes: 4

Views: 8457

Answers (5)

Jeff
Jeff

Reputation: 4209

Also:

let x = [
"kitty": 7,
"bob": 2,
"orange": 44
]
x.forEach { t in
    print("key = \(t.key); value = \(t.value)")
}

This has apparently been available since Swift 3. Link to standard library docs on Dictionary type.

Upvotes: 1

Midhun
Midhun

Reputation: 2177

Swift 4, swift5 and above

let dict: [String: Any] = ["a": 1, "b": "hello", "c": 3]

        for (key, value) in dict {
            print(key, value)
        }

Upvotes: 0

E.Coms
E.Coms

Reputation: 11531

You may try iterator like this:

 let users = ["a":11, "b":12]
 var userIds = users.values.makeIterator()
 while let next = userIds.next() {
    print(next) // 11 \n 12
 }

Upvotes: 1

iDevid
iDevid

Reputation: 517

let dictionary: [String: Int] = ["a": 1, "b": 2]

for (key, value) in dictionary {
    print(key, value)
}

Upvotes: 12

Ajay saini
Ajay saini

Reputation: 2460

You can do simply

for (_, userId) in users {
    // User setup
}

Upvotes: 1

Related Questions