mgwork
mgwork

Reputation: 9

Swift Convert Int[] to Int variable

Working with Swift 3 I got an Int array created from number and Reversed

var rev:String = String(number)
var pro:String = String(rev.characters.reversed())

var myArr = rev.characters.flatMap{Int(String($0))}
myArr = myArr.sorted { $1 < $0 }

Now i want to

var myResult = all numbers from array in one variable

Let say

myArr = [1,2,3,4]
// And i want to myResult = 1234

Or if there's any other way to reverse just a number, I mean normal Integer variable?

Upvotes: 0

Views: 3562

Answers (4)

Nirav D
Nirav D

Reputation: 72410

For that you can try like this way

let myArr = [1,2,3,4]

let myResult = myArr.map(String.init).joined()

If you want myResult as Int then

let myResult = myArr.map(String.init).joined()
if let intResult = Int(myResult) {
    print(intResult)
}

Upvotes: 3

fdiaz
fdiaz

Reputation: 2600

I'm not 100% sure what you want here. If you just want to reverse an Int then probably Martin R's solution is the best option (with simple arithmetic).

Now, if you want to sort the number and then convert it into an Int I'd recommend something like this:

let number = 1432
let string = String(String(number).characters.sorted(by: >))

let integerValue = Int(string) // Returns 4321

This will return an optional Int.

Upvotes: 0

Martin R
Martin R

Reputation: 539745

Combining the array of decimal digits to a number can be done with simple integer arithmetic:

let digits = [1, 2, 3, 4]
let result = digits.reduce(0, { $0 * 10 + $1 })
print(result) // 1234

Or if there's any other way to reverse just a number, I mean normal Integer variable?

You don't need an array or a string conversion for that purpose:

func reverse(_ n: Int) -> Int {
    var result = 0
    var n = n // A mutable copy of the given number
    while n > 0 {
        // Append last digit of `n` to `result`:
        result = 10 * result + n % 10  
        // Remove last digit from `n`:
        n /= 10
    }
    return result
}

print(reverse(12345)) // 54321

Upvotes: 5

Yannick
Yannick

Reputation: 3278

You can map your numbers to Strings, then concatenate them and convert the String to an Int.

if let result = Int(myArray.map{String($0)}.joined()) {
    //your number
}

Upvotes: 1

Related Questions