Lisa Semyonova Lisa Semyonova - 2 months ago 12
Swift Question

Can't convert dictionary to the array. Swift

Well, I am totally confused. I am trying to get the array of keys from the dictionary. This is what I wrote:

if (customerViewModel.customer._dynamicMonthCount != nil) {
var array = customerViewModel.customer._dynamicMonthCount
var months_keys = Array(arrayLiteral: array!.keys) //that does not work
}


Well, as you understood, "_dynamicMonthCount" is a dictionary:

var _dynamicMonthCount:Dictionary<String,Int>?


I give it the value as I get the data from server in json. (Actually, that dictionary is JSON Object as Dictionary).

BUT, every time I debug the program, I see that array is [LazyMapCollection<[String : Int], String>].

I tried that with different array and it works :

let dictionary = var regions:Dictionary<String,Int> = [...] //my static dictionary
var values = Array(dictionary.values) //that works
var keys = Array(dictionary.keys) //that works


Does that mean that the only problem in optional type and dynamic data? I don't know, help me, guys, please

Answer

Just delete the arrayLiteral: thing and it will work!

var months_keys = Array(array!.keys) //that does not work

The arrayLiteral initializer should be used like this:

var month_keys = Array(arrayLiteral: 1, 2, 3, 4) 
// will produce an array with items: 1, 2, 3 and 4

What you should call instead is the (_: SequenceType) initializer, since LazyMapCollection<[String : Int], String> conforms to that protocol.

A few more tips for your code:

  • If a variable's value is not going to change, declare it with let, instead of var.

  • You can simplify this:

-

if (customerViewModel.customer._dynamicMonthCount != nil) {
    var array = customerViewModel.customer._dynamicMonthCount
    var months_keys = Array(array!.keys)
}

to this:

if let dictionary = customerViewModel.customer._dynamicMonthCount {
    var months_keys = Array(dictionay!.keys)
}
Comments