Todd Thomson
Todd Thomson

Reputation: 62

Swift Dictionary with Array Values

If I declare a class property as:

var list = Dictionary<String, StructType[]>()

and then try to add a value from within a class method with:

var structType = StructType()
list[ "A" ] = [ structType ]

I get a runtime EXC_BAD_INSTRUCTION error. However, if I declare the dictionary within the class method and add a value there is no error.

It has something to do with the dictionary having values which are arrays. If I change the declaration to something simpler, like:

var list = Dictionary<String, String>() 

then within the class method:

list["A"] = "some string"

works without any issues.

Any ideas?

UPDATE:

I've also tried declaring:

var list = Dictionary<String, String[]>()

and there is no issue referencing the list within a class method.

list[ "A" ] = [ "String1", String2" ]

Also the class declaration:

var list = Dictionary<String, SomeStruct>()

can be referenced within a class method.

UPDATE 2:

The struct is defined as:

struct Firm {
    var name = ""
}

Upvotes: 1

Views: 7600

Answers (2)

Jarsen
Jarsen

Reputation: 7572

The following code appears to work for me in a playground.

struct StructType {

}

var list = [String:[StructType]]()
var structType = StructType()
list["A"] = [structType]

Upvotes: 0

Jann
Jann

Reputation: 1829

If you create your list and class in the following way it should work fine:

struct StructType {
    var myInt = 0;
}

class MyClass {
    var list = Dictionary<String, StructType[]>()
    func myFunc () {
        var structType = StructType()
        list[ "A" ] = [ structType ]
    }
}


var a = MyClass()
a.myFunc()

Upvotes: 1

Related Questions