Dogukan Inal Dogukan Inal - 1 year ago 64
Swift Question

Divide a number into digits and calculate the sum of the digits in swift

lets say i have a number 123 and i want to divide into digits like 1, 2, 3 and calculate the sum of it like 1+2+3=6. Can you help me about this?

Answer Source

You can convert number to characters and enumerate it:

let numbs = 123
let str = "\(numbs)"
let a = str.characters.reduce(0) {
    return $0 + Int("\($1)")! // Note this is an explicit unwrapped optional in production code you want to replace it with something more safety like if let
print("A: \(a)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download