Aaron
Aaron

Reputation: 6714

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.

Upvotes: 0

Views: 789

Answers (2)

vadian
vadian

Reputation: 285260

The syntax

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

is the short form for

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

which indicates a read-only property.

You need to add the setter

var dict: [String: String] {
    get {
      return [:]
    }
    set {
      dict["a"] = "b"
    }
}

But be careful, you can easily run into a infinite loop when you call the setter by itself (which it does in this example).

Actually this kind of computed property is only useful if you are going to map another value.

Upvotes: 1

Sweeper
Sweeper

Reputation: 274463

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?

Upvotes: 0

Related Questions