Oleg Gordiichuk Oleg Gordiichuk - 15 days ago 6
Swift Question

Int array to Int standart method

I am trying to convert Int array to Int number. What now i am using is converting it to String array and than use of the

joined()
function.Is there is more efficient way how it is possible to do ?

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 = 13624758

let digits = Array(sequence(state: number, next: { (num: inout Int) -> Int? in
    return num > 0 ? (num % 10, num /= 10).0 : nil
}))
print(digits) // [8, 5, 7, 4, 2, 6, 3, 1]

let descDigits = digits.sorted(by: >)
print(descDigits) // [8, 7, 6, 5, 4, 3, 2, 1]

let descNumber = descDigits.reduce(0) { 10 * $0 + $1 }
print(descNumber) // [8, 7, 6, 5, 4, 3, 2, 1]