Search code examples
swiftswift-dictionary

Swift dictionaries in class


I have problems with array of dictionaries inside classes in Swift. My code is not working in class or struct, but it works outside.

var data = [Dictionary<Int,String>]()
data.append([123: "test"])

println(data[0])
// Working OK!

class DTest {
    var data = [[Dictionary<Int,String>]]()

    func check() {
        data.append([123: "test"])
        // Error: Cannot invoke "append" with an argument list of type '([Int : String])'
        data += [123: "test"]
        // Error: Binary operator += can't be applied to operands of type ...
    }
}

Solution

  • This is because you have declared the data in class as an array of arrays of dictionaries:

    Wrong:

    var data = [[Dictionary<Int,String>]]()
    

    Fine:

    var data = [Dictionary<Int,String>]()