Aaron Aaron - 2 months ago 15
iOS Question

How to set a value on computed property

I want to set a value to a key in a computed property of type dictionary. I want to do something like this:

class Foo {
var dict: [String: String] {
dict["a"] = "b"
}
}


However that doesn't compile.


Cannot assign through subscript: 'dict' is a get-only property


I can do something like this but it's a bit verbose:

class Foo {
var values: [String: String] {
var tempValues = [String: String]()
tempValues["a"] = "b"
return tempValues
}
}


Is there a better way of doing this? For context, what I want to achieve is having
dict
by default to be an empty
[String: String]()
in a base class and when I override the property in a subclass I want to assign values to said dictionary.

Answer

and when I override the property in a subclass I want to assign values to said dictionary.

Ehh... Just do it:

class A {
    var dict: [String: String] {
        return [:]
    }
}

class B: A {
    override var dict: [String : String] {
        return ["Hello":"Hi"]
    }
}

Did you forget the override keyword?