I would like to reference more than two text field inputs using the alert.textFields?.last?.text and alert.textFields?.last?.text function, but I am unsure of how to reference the fields in between the first and last.

    let alert = UIAlertController(title: "Insert Student", message: nil, preferredStyle: .alert)
    alert.addTextField{ (tf) in tf.placeholder = "Name" }
    alert.addTextField{ (tf) in tf.placeholder = "House" }
    alert.addTextField{ (tf) in tf.placeholder = "Score" }

    let action = UIAlertAction (title:"Submit", style: .default) { (_) in
        guard let name = alert.textFields?.first?.text,
        let house = alert.textFields?.last?.text,
            let score = alert.textFields?.last?.text

1 Answers

1
Brkr On
let alert = UIAlertController(title: "Insert Student", message: nil, preferredStyle: .alert)
    alert.addTextField{ (tf) in
        tf.placeholder = "Name"
        tf.tag = 11
    }
    alert.addTextField{ (tf) in
        tf.placeholder = "House"
        tf.tag = 12
    }
    alert.addTextField{ (tf) in
        tf.placeholder = "Score"
        tf.tag = 13
    }

    let action = UIAlertAction (title:"Submit", style: .default) { (_) in
        guard let nameTextField = alert.view.viewWithTag(11) as? UITextField,
            let houseTextField = alert.view.viewWithTag(12) as? UITextField,
            let scoreTextField = alert.view.viewWithTag(13) as? UITextField else { return }

        guard let name = nameTextField.text,
            let house = houseTextField.text,
            let score = scoreTextField.text else { return }
    }