I've two variables number
and number2
with String
value, I want to convert those Strings to Int and add to each other,but the compiler returns error: Binary operator ' ' cannot be applied to two 'Int?' operands
.
var n1 = "6"
var number = n1 "5"
Int(number)
var n2 = "3"
var number2 = n2 "5"
var finalNumber = Int(number2) Int(number)
print(finalNumber)
I want summary of Int
numbers and not strings. expected result: 19
CodePudding user response:
Because converting a String
to an Int
can be a failing operation, say converting A
into an Int
, you are using a failable initializer.
This means that you are getting Int?
as a result. In your first example, you get a result of Optional(65)
when printed. In playgrounds, the optional's value, of just 65
, is shown instead.
The problem arrises that you can't add Int?
together with the
operator, only two Int
s.
You can fix the problem by providing a default value if the conversion failed and the result is nil
:
var finalNumber = Int(number2) ?? 0 (Int(number) ?? 0)