Chris Chris - 1 month ago 21
Swift Question

String to Int in Swift 3.0

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

Answer
  1. Use components(separatedBy:) to break up the comma-separated string.
  2. Use trimmingCharacters(in:) to remove spaces before and after each element
  3. Use Int() to convert each element into an integer.
  4. Use flatMap to remove any items that couldn't be converted to Int.
  5. Use reduce to sum up the array of Int.

    let input = " 98 ,99 , 97, 96 "
    
    let values = input.components(separatedBy: ",").flatMap { Int($0.trimmingCharacters(in: .whitespaces)) }
    let sum = values.reduce(0, +)
    print(sum)  // 390
    
Comments