user1760153
user1760153

Reputation: 291

Setter for computed property of type Dictionary

I am new to swift and I am using swift 4.0. I have a class with computed property of type Dictionary. I am using getter and setter for this property. Below is my property snippet.

var responses:[String:Float] {
    get {
        let newresponses = self.calculateResponses(with: self.Range)
        return newresponses
    }
    set {

    }
}

How do I code setter so it allows me to update value for specific key? For example, in one of my func I need to update value for responses for a specific key.

self. responses[key] = newResponse 

Thank you.

Upvotes: 0

Views: 1258

Answers (1)

Robert Dresler
Robert Dresler

Reputation: 11210

You can't do this with computed property. Because every time you're trying to get responses you're actually getting result of self.calculateResponses(with: self.Range).

To solve this just create empty dictionary

var responses = [String : Float]()

and then when you need to assign new value use this

responses[key] = newResponse

or if you need to assign all new dictionary use this

responses = self.calculateResponses(with: self.Range)

Upvotes: 1

Related Questions