0
votes

This example Swift code does not compile if SomeClass is defined as struct. The compiler says: @value $T6 is not identical to (String, Proto)

However, the compiler does not complain if SomeClass is a class.

Why?


public protocol Proto {
    func hello(value:Int)
}


public struct SomeClass {

    var map = [String:Proto]()

    public func store (key:String, value:Proto) {

        map[key] = value // That does not work if SomeClass is a struct  

    }
}


1

1 Answers

2
votes

Because you modify the element of the struct in the store function, and if you do so, you have to add the "mutating" prefix to it. So:

public mutating func store (key:String, value:Proto) {

    map[key] = value // That does not work if SomeClass is a struct

}

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.