0

Not sure how tag a question. I want to create an array of Int values from Int value. For example, if i have 1234 i want to output [1,2,3,4], for 8765 [8,7,6,5] etc. Function should look like:

private static func formAnArray(_ value: Int) -> [Int] {
// code
}
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

2 Answers2

1

You can convert number to String and map it to array:

private static func formAnArray(_ value: Int) -> [Int] {
    return String(value).compactMap { Int(String($0)) }
}

Another way (preferred for big numbers) is by using combination of % and /:

private static func formAnArray(_ value: Int) -> [Int] {
    var value = value
    var result: [Int] = []
    while value > 0 {
        result.insert(value % 10, at: 0)
        value /= 10
    }
    return result
}
pacification
  • 5,838
  • 4
  • 29
  • 51
1

You can use compactMap to get and convert digits to an array of int

print(formAnArray(value: 1234))
func formAnArray(value: Int) -> [Int] {
    let string = String(value)
    return string.compactMap{Int(String($0))}
}
Bhavik Modi
  • 1,517
  • 14
  • 29