A "normal" for..in loop on an array handles the elements in the order you would expect. But not this one.
Go ahead and try this in a playground. Every time it runs, I get a different ordering of the keys and never get back 1,2,3,4,5 as entered. If I make another loop around the loop shown (as commented out), it'll give the same key order for each iteration. But a different key order appears when the whole thing is rerun.
Confused.
import UIKit
let dataTable: [String: [Double]] = [
"1Cat": [99.95, 0, 0.05, 0, 0, 0, 0.04],
"2Dog": [1, 1, 0, 98, 0, 0, 0.2],
"3Mouse": [49.0, 43.2, 3.9, 0, 0.2, 3.7, 0.05],
"4Gerbil": [40.3, 55.4, 3.0, 0, 0.4, 0.9, 0.05],
"5Fish": [7.7, 90.8, 1.2, 0, 0.1, 0.2, 0.05]]
for i in dataTable {
print(i)
}
// for j in 1...4 {
// for i in dataTable {
// print(i)
// }
// print("\n")
// }
I don't understand your point
I ran this:
let dataTable: [String: [Double]] = [
"1Cat": [99.95, 0, 0.05, 0, 0, 0, 0.04],
"2Dog": [1, 1, 0, 98, 0, 0, 0.2],
"3Mouse": [49.0, 43.2, 3.9, 0, 0.2, 3.7, 0.05],
"4Gerbil": [40.3, 55.4, 3.0, 0, 0.4, 0.9, 0.05],
"5Fish": [7.7, 90.8, 1.2, 0, 0.1, 0.2, 0.05]]
for i in dataTable {
print(i)
}
print("\n Second form\n")
for j in 1...4 {
for i in dataTable {
print(i)
}
print("\n")
}
And got same results for each:
(key: "4Gerbil", value: [40.3, 55.4, 3.0, 0.0, 0.4, 0.9, 0.05])
(key: "1Cat", value: [99.95, 0.0, 0.05, 0.0, 0.0, 0.0, 0.04])
(key: "3Mouse", value: [49.0, 43.2, 3.9, 0.0, 0.2, 3.7, 0.05])
(key: "2Dog", value: [1.0, 1.0, 0.0, 98.0, 0.0, 0.0, 0.2])
(key: "5Fish", value: [7.7, 90.8, 1.2, 0.0, 0.1, 0.2, 0.05])
Second form
(key: "4Gerbil", value: [40.3, 55.4, 3.0, 0.0, 0.4, 0.9, 0.05])
(key: "1Cat", value: [99.95, 0.0, 0.05, 0.0, 0.0, 0.0, 0.04])
(key: "3Mouse", value: [49.0, 43.2, 3.9, 0.0, 0.2, 3.7, 0.05])
(key: "2Dog", value: [1.0, 1.0, 0.0, 98.0, 0.0, 0.0, 0.2])
(key: "5Fish", value: [7.7, 90.8, 1.2, 0.0, 0.1, 0.2, 0.05])
SAME AFTER 3 times
I assume the same for you ?
Did a second run and got a different key ordezr:
(key: "2Dog", value: [1.0, 1.0, 0.0, 98.0, 0.0, 0.0, 0.2])
(key: "3Mouse", value: [49.0, 43.2, 3.9, 0.0, 0.2, 3.7, 0.05])
(key: "1Cat", value: [99.95, 0.0, 0.05, 0.0, 0.0, 0.0, 0.04])
(key: "4Gerbil", value: [40.3, 55.4, 3.0, 0.0, 0.4, 0.9, 0.05])
(key: "5Fish", value: [7.7, 90.8, 1.2, 0.0, 0.1, 0.2, 0.05])
Second form
(key: "2Dog", value: [1.0, 1.0, 0.0, 98.0, 0.0, 0.0, 0.2])
(key: "3Mouse", value: [49.0, 43.2, 3.9, 0.0, 0.2, 3.7, 0.05])
(key: "1Cat", value: [99.95, 0.0, 0.05, 0.0, 0.0, 0.0, 0.04])
(key: "4Gerbil", value: [40.3, 55.4, 3.0, 0.0, 0.4, 0.9, 0.05])
(key: "5Fish", value: [7.7, 90.8, 1.2, 0.0, 0.1, 0.2, 0.05])
SAME AFTER 3 times
This is absolutely normal. What did you expect ?
Your title says:
Unexpected for...in array behavior
But that's not in array, that's in dictionary.
So it is normal, order is not fixed in a dictionary and may change each time you invoke the dictionary.