I need to write something like the following:
var dict = [SomeEnum: SomeObject]()
var someValue: SomeObject! = dict[.case1]
if someValue == nil {
someValue = someDefaultValue
dict[.case1] = someValue
}
The Nil-coalescing operator already exists but it doesn't mutate the original dictionary. The same is for dict[.case1, default: someDefaultValue.
Could you please explain how to write a new subscript/operator to wrap the code above?
You can create custom subscripts by declaring a new method using the
subscriptkeyword instead of thefunckeyword.Based on your requirements, it seems you only need your custom subscript to have a getter, you don't need a setter for it - you can use the default setter to set values.
Usage example: