2
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

Graycodder
  • 447
  • 5
  • 15
  • Essentially a duplicate of [Multiple variable assignment in Swift](https://stackoverflow.com/questions/26155523/multiple-variable-assignment-in-swift). – Martin R Jun 06 '20 at 07:53
  • See also [increment Error in swift 3](https://stackoverflow.com/questions/39704971/increment-error-in-swift-3) – Martin R Jun 06 '20 at 07:54
  • What I mean is set value of "a" to dictionary and then increment. How can it possible in one line – Graycodder Jun 06 '20 at 08:09

3 Answers3

2

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
Wide Angle Technology
  • 1,184
  • 1
  • 8
  • 28
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
}
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
0

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)
Joby Ingram-Dodd
  • 730
  • 5
  • 23