Search code examples
swiftdictionarycasting

Increment number in Dictionary


I have a Dictionary [String:AnyObject] which contains some keys and values.

I want to increment a key to which value is of type Double.

I can do it this way:

let nr = dict["number"] as! Double
dict["number"] = nr + 10

But I dont like that way so Im wondering if there is another way

I tried this:

(dict["number"] as! Double) += 10

But that gives me an error:

Binary operator '+=' cannot be applied to operands of type '(Double)' and 'Double'

Why isn't this working?


Solution

  • You are close and in fact you can write to a dictionary using +=, the problem is your cast. For example we can do:

    var dict = ["number" : 2]
    dict["number"]! += 10
    

    and now dict["number"] returns 12. Now this is creating a new value (12) and replacing it into the dictionary, it is just a clean way of looking at it.

    The problem with your code is that the left side (dict["number"] as! Double) gives you a Double. So you have say (12), then the right side is a Double too (10). So your code ends up looking like (12) += 10 which you can clearly see as problematic, since this is equivalent to 12 = 12 + 10, yikes!

    So that being said, you can use the my first solution if you are working with native Swift dictionaries, otherwise your solved solution above works too, just a bit longer.

    Lastly, if you are really looking for a one liner that works with your exact situation you should be able to do something like:

    dict["number"] = (dict["number"] as! Double) + 10