1

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

2
  • 1
    Does this answer your question? Converting String to Int with Swift Commented Sep 30, 2021 at 13:01
  • 65 + 35 should be equal to 100 Commented Sep 30, 2021 at 17:02

1 Answer 1

1

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 Ints.

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.