Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String convert to Int and replace comma to Plus sign

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

like image 717
Chris Avatar asked Oct 15 '16 21:10

Chris


1 Answers

  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 compactMap (previously called 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: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) } let sum = values.reduce(0, +) print(sum)  // 390 
like image 175
vacawama Avatar answered Sep 22 '22 08:09

vacawama