Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

swift - How to split an Int to its individual digits?

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 number into a string and then iterating over each digit, but it doesn't work:

var number = "123456"

var array = [Int]()

for digit in number {
    array.append(digit)
}

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...