Using Swift, I'm trying to take a list of numbers input in a text view in an app and create a sum of this list by extracting each number for a grade calculator. Also the amount of values put in by the user changes each time. An example is shown below:
String of: 98,99,97,96... Trying to get: 98+99+97+96...
Please Help! Thanks
components(separatedBy:) to break up the comma-separated string.trimmingCharacters(in:) to remove spaces before and after each elementInt() to convert each element into an integer.compactMap (previously called flatMap) to remove any items that couldn't be converted to Int.Use reduce to sum up the array of Int.
let input = " 98 ,99 , 97, 96 " let values = input.components(separatedBy: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) } let sum = values.reduce(0, +) print(sum) // 390 If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With