简体   繁体   中英

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?

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

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)
}

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM