Graycodder
Graycodder

Reputation: 467

How to assign value after increment Swift?

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

Upvotes: 2

Views: 223

Answers (3)

Jawad Ali
Jawad Ali

Reputation: 14397

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
}

Upvotes: 1

Joby Ingram-Dodd
Joby Ingram-Dodd

Reputation: 730

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)

Upvotes: 0

Wide Angle Technology
Wide Angle Technology

Reputation: 1222

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

Upvotes: 2

Related Questions