Oleg Gordiichuk Oleg Gordiichuk - 16 days ago 5
Swift Question

Int array to Int standard method

I am trying to convert an

Int
array to an
Int
number. What I am now
doing is converting it to a
String
array and then use the
joined()
function. Is there a more efficient way to do this?

Example:

let sortedIntArray = String(number).characters.map{Int(String($0)) ?? 0}.sorted(by: { $0 > $1 })

let desOrder = Int(sortedIntArray.map{String($0)}.joined())!

Answer

In your case, sortedIntArray is an array of single-digit numbers, and then you can combine them without any conversion to strings:

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

Combined with the dfri's elegant solution to split the number into an integer array:

let number = 1439

let descDigits = sequence(state: number, next: { (num: inout Int) -> Int? in
    return num > 0 ? (num % 10, num /= 10).0 : nil
}).sorted(by: >)
print(descDigits) // [9, 4, 3, 1]

let descNumber = descDigits.reduce(0) { 10 * $0 + $1 }
print(descNumber) // 9431