How to split an Int to its individual digits?

后端 未结 8 1238
误落风尘
误落风尘 2020-12-13 06:18

I am trying to split an Int into its individual digits, e.g. 3489 to 3 4 8 9, and then I want to put the digits in an Int array.

I have already tried putting the num

相关标签:
8条回答
  • 2020-12-13 07:16

    We can also extend the StringProtocol and create a computed property:

    edit/update: Xcode 11.5 • Swift 5.2

    extension StringProtocol  {
        var digits: [Int] { compactMap(\.wholeNumberValue) }
    }
    

    let string = "123456"
    let digits = string.digits // [1, 2, 3, 4, 5, 6]
    

    extension LosslessStringConvertible {
        var string: String { .init(self) }
    }
    
    extension Numeric where Self: LosslessStringConvertible {
        var digits: [Int] { string.digits }
    }
    

    let integer = 123
    let integerDigits = integer.digits // [1, 2, 3]
    
    let double = 12.34
    let doubleDigits = double.digits   // // [1, 2, 3, 4]
    

    In Swift 5 now we can use the new Character property wholeNumberValue

    let string = "123456"
    
    let digits = string.compactMap{ $0.wholeNumberValue } // [1, 2, 3, 4, 5, 6]
    
    0 讨论(0)
  • 2020-12-13 07:19

    Swift 5

    extension Int {
        func digits() -> [Int] {
            var digits: [Int] = []
            var num = self
            
            digits.append(num % 10)
            
            while num >= 10  {
                num = num / 10
                digits.append(num % 10)
            }
            
            return digits.reversed()
        }
    }
    
    0 讨论(0)
提交回复
热议问题