I am trying to calculate the sum of user inputs to UITextFields that are in an IBOutletCollection...HELP!

So as the title suggest, I have a series of UITextFields that the user will input integers (even though it will be saved as a string) and I would like to simply find the sum of those integers. I have collected the 9 TextFields together in an IBOutletCollection, so they are already in an array, and I would like to convert the independent values into Integers, and find the sum of those numbers to display back to the user (technically a running total as they enter values).

Here is the code I have… most of the online solutions have led to bugs and errors from past versions of Swift. I am on the current version.

import UIKit

class ViewController: UIViewController {

     @IBOutlet var playerScores: [UITextField]!

     @IBOutlet weak var front9Total: UILabel!

     override func viewDidLoad() {
           super.viewDidLoad()
    
  //  intPlayerScores = playerScores.map {Int($0)!}
    // Do any additional setup after loading the view.
}
//let intPlayerScores = Array<Int>()

}

Hey @Garrett_Kelley,

To turn the values of your array into integers, try using the .map function. Check this link out: https://stackoverflow.com/questions/33348056/convert-string-array-into-int-array-swift-2

As for the sum of the values, check this link out: https://stackoverflow.com/questions/24795130/finding-sum-of-elements-in-swift-array.

Let me know if this worked out for you

intPlayerScores = playerScores.compactMap({ Int($0.text!) }).reduce(0, +)

compactMap will strip out any values that are nil, which could happen if the user enters something that isn’t convertible to an Int, and then reduce will generate a single value from the remaining Ints using the + operator.

You almost certainly wouldn’t want it in your viewDidLoad, however, because that runs when the view loads into memory, which should be well before the user has a chance to enter any text.