How to assign value after increment Swift?

Viewed 147
var str = ["Franc": 2]
var a = 1
str["Franc"] = a += 1
print(str)

When I try this code i get an error on line "str["Franc"] = a += 1" that is "Cannot assign value of type '()' to type 'Int?'" How to solve this. I need it in single line Thank you in advance

3 Answers

We can do this directly only in Objective C:

In Objective C:

[str setValue:[NSNumber numberWithInt:a+=1] forKey:@"Franc"];

In Swift

str["Franc"] = a
a += 1

You can increment number like this

str["Franc"]! = a ; a += 1

assign value

var str = ["Franc": 2]
str["Franc"]! += 1

and now str["Franc"] will returns 3

And if you want to avoid force unwrapping

str["Franc"] = (str["Franc"] ?? 0) + 1 

Also you can do it using if let

if let num = str["Franc"] as? Double {
    str["Franc"] = num + 1
}

I don't think you can do this in a single line:

var str = ["Franc": 2]
var a = 1
str["Franc"] = a 
a += 1
print(str)
Related