简体   繁体   中英

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 = ""
}

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()

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

struct StructType {

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM