Yusuf X
Yusuf X

Reputation: 14633

Swift dictionary member compile error

When I make a dictionary a member, assignment doesn't compile:

struct MyClass {
var lists = [String:Int]();
init() {}

func add() {

    // this compiles
    var x = [String:Int]();
    x["y"] = 3;

    // this gets the compiler error 'cannot assign to the result of this expression'
    self.lists["y"] = 3;
}

What is it about membership that breaks the compilation? I don't get this error if I put that line in init() FWIW.

Upvotes: 1

Views: 57

Answers (1)

Lucas Huang
Lucas Huang

Reputation: 4016

You need to add mutating from the function declaration like this because properties are readonly if you don't specify that keyword in struct:

mutating func add()

Upvotes: 2

Related Questions