NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to split an integer into an array of its digits

Swift version: 5.2

Paul Hudson    @twostraws   

You can take any integer number and convert it to array of integer digits using this extension:

extension BinaryInteger {
    var digits: [Int] {
        return String(describing: self).compactMap { Int(String($0)) }
    }
}

That’s a protocol extension, so you should be able to call it using Int, UInt64, Int8, and so on.

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Ever ask for help and your reviewer immediately notices issues you missed? Fernando Olivares is a 10-year veteran from Big Nerd Ranch and Lambda School who can help hone your app building skills, and he's just launched a new book that does just that – use the code "hacking" to save $5!

Buy the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.0/5

Link copied to your pasteboard.