Jayps_T - 3 years ago 181
Swift Question

# Sum of digits of each elements inside an array of integers (Swift)

In swift 3, how to calculate each integers inside the arrays.

Example:

``````var nums = [111,222,333]
``````

The answer should be like this:
`[3,6,9]`

You could implement it as follows:

``````let nums = [111,222,333]

func transform(_ element: Int) -> Int {
var intsChars: [Int] = []
for char in "\(element)".characters {
intsChars.append(Int(String(char))!)
}

return intsChars.reduce(0, +)
}

let result = nums.map { transform(\$0) }

print(result) // [3, 6, 9]
``````

UPDATE:

As mentioned in Martin R's answer:

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

you could also achieve the same output:

``````let result = nums.map { digitSum(\$0) } // [3, 6, 9]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download