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 calledflatMap
) to remove any items that couldn't be converted toInt
.Use
reduce
to sum up the array ofInt
.let myString = "556" let myInt = Int(myString)
For Swift 3 and Swift 4.
Simple way: Hard coded. Only useful if you know the exact amount of integers coming up, wanting to get calculated and printed/used further on.
print(finalInt) // prints Optional(398) (optional)
Fancy way as a function: Generic way. Here you can put as many strings in as you need in the end. You could, for example, gather all the strings first and then use the array to have them calculated.
print(result) // prints 398 (non-optional)