For loop iterates an array in Swift Playground in random order

why does the for loop in Swift Playground iterates over each element in a random order? I thought for loops iterate from the first element going to the last?

Answered by Claude31 in 765786022

What does surprise you ? Is it this order:

key: Prime
key: Square
key: Fibonacci 

and the fact that it changes at each iteration ?

key: Square
key: Prime
key: Fibonacci 

That's normal in Swift (not specific to playgrounds).

That's because you loop through a dictionary and there is no order in a dictionary, contary to Array. Note that there is no order either in Sets.

That's explicit in Swift programming Language :

Accepted Answer

What does surprise you ? Is it this order:

key: Prime
key: Square
key: Fibonacci 

and the fact that it changes at each iteration ?

key: Square
key: Prime
key: Fibonacci 

That's normal in Swift (not specific to playgrounds).

That's because you loop through a dictionary and there is no order in a dictionary, contary to Array. Note that there is no order either in Sets.

That's explicit in Swift programming Language :

hi,

your iteration is over the elements of a dictionary that has three key-value pairs:

for (key ‚numbers) in interestingNumbers {  // interestingNumbers is not an array

dictionaries are not ordered; so one time you may get Fibonacci, Prime, Square ... another time it may come out in a different order. this is exactly the behavior that you're seeing.

hope that helps,

DMG

What Claude31 and DelawareMathGuy said plus…

This isn’t accidental. Swift goes out of its way to prevent any sort of stable ordering for dictionary iteration because that can lead to hash flooding attacks. It has the added benefits of highlighting problems like this, where folks mistakenly relying on dictionary key ordering.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

For loop iterates an array in Swift Playground in random order
 
 
Q