Search code examples
swiftswift5swift-playground

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


Solution

  • 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