0

I have a bunch of textFields which content I want to add to a array
I have tried different approaches, and I got it working with this method:

@IBAction func addToArrayTapped(_ sender: UIButton) {

        if let fromTextField1 = textField1.text {
            array.append(fromTextField1)
        }
        if let fromTextField2 = textField2.text {
            array.append(fromTextField2)
        }
        if let fromTextField3 = textField3.text {
            array.append(fromTextField3)
        }
        print(array) 
}    

Is this really the correct way to add content from a textField to a array? It feels a bit complicated.

2 Answers 2

2

You can do

let arr = [textField1,textField2,textField3].map { $0.text! }

Also you can create outlet collection for all textfields in IB like

@IBOutlet weak var allTextF:[UITextField]!

instead of individually hooking each one

Sign up to request clarification or add additional context in comments.

2 Comments

For the sake of the OP and others that are not aware, this is a case where it is perfectly safe to force unwrap a value. It is documented that the text property of UITextField can safely be unwrapped because even if you set it to nil, you will get "".
In addition to that in other cases it's not wrong to directly use ! when there is 100% possibility that the value will never be nil otherwise it's the place for if let or guard
0

There is an easy way:


    // Here you can use IBOutlet collection or form textFields array programmatically
    let textFields = [textField1, textField2, textField3] 
    let result = textFields.compactMap { $0.text }

And no force unwraps. Type of result is [String].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.