Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 213
Arbitur Avatar asked May 20 '15 16:05

Arbitur


1 Answers

Following is an alternative. If you want to avoid force unwrapping an optional:

dict["number"] = (dict["number"] ?? 0) + 10
like image 55
nananta Avatar answered Nov 15 '22 09:11

nananta