Grumdrig
Grumdrig

Reputation: 16975

Swift: Can't add value to dictionary member of struct

I can't add a value to a dictionary that is a member of a struct. For example, this:

struct S {
  var d = [String:Int]()

  func f() {
    d["Hello"] = 0
  }
}

results in this error:

'@lvalue $T6' is not identical to '(String, Int)'

Changing struct to class, or moving the declaration of d into function scope removes the error.

I imagine this is a bug, but I don't know. Is there some logic to this I don't understand?

Upvotes: 1

Views: 1232

Answers (2)

Logan
Logan

Reputation: 53132

Does it need to be mutating for a struct?

Struct S {
  var d = [String:Int]()

  mutating func f() {
    d["Hello"] = 0
  }

I'm on mobile, so let me know if it doesn't work and I'll pull the answer.

Upvotes: 1

Bryan Chen
Bryan Chen

Reputation: 46598

you need to mark the method with mutating keyword to indicate it does modify the struct

mutating func f() {
  d["Hello"] = 0
}

From doc

Modifying Value Types from Within Instance Methods

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.

You can opt in to this behavior by placing the mutating keyword before the func keyword for that method:

Upvotes: 4

Related Questions