Search code examples
iosswiftloggingiboutletcollection

Add textfield outlet collection together


I want to print the total of all of the textfields connected to cool textfield collection. There are only 2, in the log file.

import UIKit

class ViewController: UIViewController {
    @IBOutlet var cool: [UITextField]!

    @IBAction func press(_ sender: Any) {
        for view in cool {
   ((cool.text! as NSString).integerValue +=  ((cool.text! as NSString).integerValue
        }
    }
}

Solution

  • If you want to add up all of the text fields, then simply do:

    @IBAction func press(_ sender: Any) {
        var total = 0
        for view in cool {
            if let text = view.text, let num = Int(text) {
                total += num
            }
        }
    
        print("The total is \(total)")
    }
    

    Don't force unwrap optionals. Don't use NSString in Swift.