how to append integers and convert to one Integer

Can I append two integers (for example)


let firstNumber = 2
let secondNumber = 3

and I want the result number integer equal 23


how to do doing that?

Accepted Reply

Convert to string, append strings and back to Int.


let firstNumber = 2
let secondNumber = 3

let jointStr = String(firstNumber) + String(secondNumber)
let val = Int(jointStr) ?? 0

Replies

Convert to string, append strings and back to Int.


let firstNumber = 2
let secondNumber = 3

let jointStr = String(firstNumber) + String(secondNumber)
let val = Int(jointStr) ?? 0

thanx bro, and if want the opposite, I mean when I want to convert Integer like 71 to two integers

(7) and (1).

what's the best way to doing that.

You should try by yourself, in playground.


But think better of your spec:

if number is 2 digits, OK

But what about a number as 125 ? How do you want to split ?


So let's look for a number btween 0 and 99


just do this


let number = 71
var firstNumber = 0
var secondNumber = 0

if number < 0 || number > 99 {
    print("I will not split")
} else {
    secondNumber = number % 10 // That will be units : 1
    firstNumber = (number - secondNumber)  / 10 // that will be tens : 7
}

thanx bro, I sure my numbers contain two numbers only.

but Is this method work when my number is (01)?

Why do you thinkt it could not work ?


Try in playground and you will see the (good) result.