Dogukan Inal Dogukan Inal - 4 months ago 28
Swift Question

How to sum of the digits of an Int

I have an

Int
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
6
.

Can you help me?

Answer

Given this

let number = 123

You can

let digitsSum = String(number)
    .characters
    .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.

Comments