1

I have problem with data that assign to array dictionary, and it is not in the order. This is my code you can test:

let arrayDataTest   = ["1","2","3","4"];
var myarray         = [String:[AnyObject]]()
var arrayAdd        = [AnyObject]()

 for i in 0...arrayDataTest.count - 1{
   var dayArray = [String:AnyObject]()
   dayArray["month"]    = arrayDataTest[i]
   arrayAdd.removeAll()
   arrayAdd.append(dayArray)          
   let string = arrayDataTest[i]
   myarray[string] = arrayAdd
}

Result for loop that i want is : 1,2,3,4 but my problem loop result is 4,2,1,3 . I don't know why? Thank

Nirav D
  • 71,513
  • 12
  • 161
  • 183
Pheaktra Ty
  • 338
  • 3
  • 8
  • Possible duplicate of [How Are Dictionary Keys Sorted In Swift?](http://stackoverflow.com/questions/38616208/how-are-dictionary-keys-sorted-in-swift) – Daniel Jul 28 '16 at 11:57

2 Answers2

1

First of all you have decalre myarray as of dictionary type not array type. In dictionary you can not control the order of key. So the output you are getting for your for loop it doesn't have any wrong output it is working correctly.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
0

Your code is equivalent to:

let myArray = ["1","2","3","4"].map { [["month": $0]]}

Note that, like in your code, myArray is an array of arrays of dictionaries and each dictionary is contained in an array with exactly one element (which is a bit strange).

myArray is [[["month": "1"]], [["month": "2"]], [["month": "3"]], [["month": "4"]]]

To get each element in order just do something like:

for element in myArray {
    print(element)
}

The output would be:

[["month": "1"]]
[["month": "2"]]
[["month": "3"]]
[["month": "4"]]
Daniel
  • 20,420
  • 10
  • 92
  • 149