1

I defined Dictionary in Swift, with enum as the key and struct as value. At runtime I want to add value to the dictionary for a given enum key, however I get the following error:

'@lvalue $T9' is not identical to '(MyEnum, MyData)'

enum MyEnum {
    case A, B, C
}

struct MyData {

    var x : Int
    var y : Int

    init(x:Int, y: Int) {
        self.x = x
        self.y = y
    }
} 

class Tester {

    let myDictionary = [MyEnum : MyData]()

    func dummy() {
        self.myDictionary[MyEnum.A] = MyData(x: 1, y: 2) // <-- error in this line
    }
}

Any idea how to do it properly ?

Tamir
  • 625
  • 1
  • 12
  • 27

1 Answers1

2

The problem is that you’ve declared myDictionary with let rather than var. Switch it to var and your code will work as expected.

Dictionaries are structs, which are a “value” type. That means when you declare them with let, they are frozen forever with the value they were assigned. You can’t call methods that change their value, including assigning to them via a subscript ([ ]).

Unfortunately the error message isn’t super-helpful. Ideally it would read something like “attempt to modify immutable value myDictionary”.

Don’t let this put you off using let though – it’s a great practice to use let by default unless you know you need to change a value. But in this instance you do, so you need to use var.

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
  • Thanks. Great answer. It works. btw, as I understand there's no way to have enum with properties (like in Java for example), otherwise I wouldn't have to define this additional dictionary and could combine the enum and its related struct data. Am I right ? – Tamir Dec 28 '14 at 12:35
  • Enums can have both raw underlying types and associated values. The link mentioned in the comment as a possible duplicate of your question was about how enums with associated values aren’t automatically hashable, take a look at that, or you can read the enums chapter in [the Swift book](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-ID145) – Airspeed Velocity Dec 28 '14 at 12:43
  • I read the explanation about raw value, however it doesn't look the same as in Java where you can define enum with fixed values, like example 3 in the following page: http://javarevisited.blogspot.co.il/2011/08/enum-in-java-example-tutorial.html – Tamir Dec 28 '14 at 13:09
  • Not sure exactly which one you mean by example 3 but this is an equivalent of what I think you mean: `enum Currency: Int { case Penny = 1 case Nickle = 5 case Dime = 10 case Quarter = 25 }; let coin = Currency(rawValue: 25)` – Airspeed Velocity Dec 28 '14 at 13:14
  • yes, this is what I meant, but what you wrote is not exactly as in the java example... according to this example I would like to write let coin = Currency.Quarter. And Quarter can holds also some other attributes... – Tamir Dec 28 '14 at 13:27