Dogukan Inal Dogukan Inal - 1 year ago 115
Swift Question

How to sum of the digits of an Int

I have an

like this

let num: Int = 123

Now I want to split it into digits like
1, 2, 3
and sum them in order to get

Can you help me?

Answer Source

Given this

let number = 123

You can

let digitsSum = String(number)
    .flatMap { Int(String($0)) }
    .reduce(0, combine: +)

How does it work?

String(number) The first instruction convert your Int into a String so now we have "123"

.characters This extract an array of Characters so the output is ["1", "2", "3"]

.flatMap { Int(String($0)) } This convert the array of Characters into an array of Int so [1, 2, 3]

.reduce(0, combine: +) Finally each element of the array of Int is combined with the + operation. So 1 + 2 + 3.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download