Search code examples
swiftenumssubscript-operator

How to implement swift subscript setter for enum associated value


Trying to get the following to work:

enum Foobar {
    case values([Int])
    case singleThing(Double)

    subscript(index:Int) -> Int? {
        get {
            switch self {
            case .values (let numbers):
                return numbers[index]
            default:
                return nil
            }
        }
        set {
            switch self {
            case .values (let numbers):
                numbers[index] = newValue!
            default:
                break
            }
        }
    }
}

The above code won't compile. It complains about the fact that I'm updating numbers when I assigned it with a let. So I tried replacing that let with var. Which compiles. But does nothing, because the it updates a value copy of the associate array, rather than the original array itself. At least that's what I think happens.

Is there an approach that will allow me to have associated values that are subscriptable and implement the set property when appropriate?


Solution

  • In

    case .values (let numbers):
        numbers[index] = newValue!
    

    numbers is a local variable which is bound to the current associated value. Even with var numbers, you modify only this variable, not the instance of the enumeration.

    case .values (var numbers):
        numbers[index] = newValue!
        self = .values(numbers)
    

    should do what you expect. (Note however that calling the subscript setter with nil will crash your program.)