bmaliel - 1 year ago 117

Swift Question

Does anyone know how to get the sum of all the digits in a number in Swift?

For example using the number

`845`

`17`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Here is a solution that uses simple integer arithmetic only:

```
func digitSum(var n : Int) -> Int {
var sum = 0
while n > 0 {
sum += n % 10 // Add least significant digit ...
n /= 10 // ... and remove it from the number.
}
return sum
}
println(digitSum(845)) // 17
```

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