Pushpa Raja
Pushpa Raja

Reputation: 652

Crash while getting value from the dictionary in Swift

I have created a dictionary like

var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:Array] = ["key1":["value1"],"key2":["value2",6,tempArray2]]

The application crashed when I tried to print all values from the dictionary like

let allValues = [Array](dictionary.values)
for value in allValues{
     println(value)
}

I just started learning dictionary concept in swift language. I want to know my approach is right or wrong. Please help me to figure it out

Upvotes: 0

Views: 3202

Answers (2)

Uttam Kumar
Uttam Kumar

Reputation: 169

You can try this also

var tempArray1 = ["sdds","dsads"]  
var tempArray2: AnyObject = ["sddsa",34,tempArray1]

println("Array inside array \(tempArray2)")
    var dictionary: [String:Array] = ["key1":["value1"],"key2":["value2",6,tempArray2]]

    println(dictionary)

    let allValues = Array(dictionary.values)
    for value in allValues{
        println(value)
    }

Upvotes: 2

Kirsteins
Kirsteins

Reputation: 27345

As Swift arrays have associated I don't think that you can declare type with array without specifying its associated type. I am not sure why you do not get compile time errors. This should work:

var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:Array<AnyObject>] = ["key1":["value1"],"key2":["value2",6,tempArray2]]

let allValues = [Array<AnyObject>](dictionary.values)
for value in allValues{
    println(value)
}

Or even shorter:

var tempArray1 = ["sdds","dsads"]
var tempArray2: AnyObject = ["sddsa",34,tempArray1]
var dictionary: [String:[AnyObject]] = ["key1":["value1"],"key2":["value2",6,tempArray2]]

let allValues = dictionary.values
for value in allValues{
    println(value)
}

Upvotes: 2

Related Questions