Reputation: 412
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.
Upvotes: 0
Views: 382
Reputation: 114
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].
Upvotes: 0
Reputation: 100551
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
Upvotes: 2