Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop over a dictionary in Swift 5?

Tags:

swift

swift5

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?

like image 324
Nico S. Avatar asked Oct 26 '25 16:10

Nico S.


2 Answers

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

for (key, value) in dictionary {
    print(key, value)
}
like image 102
iDevid Avatar answered Oct 28 '25 07:10

iDevid


You can do simply

for (_, userId) in users {
    // User setup
}
like image 35
Ajay saini Avatar answered Oct 28 '25 08:10

Ajay saini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!