Kayan
Kayan

Reputation: 51

Swift: how to assign a string array to the text property of an array of UITextFields?

If I have 2 string arrays, it'd be fairly simply to assign one to the other in one line of code (w/o having to use a for-loop):

var sArray1 = ["A","B","C"]
var sArray2 = sArray1

However, I'd like to do something similar with an array of UITextFields, but can't figure it out. I feel like it should look something like this:

var sArray1 = ["A","B","C"]
var sArray2 = [textField1, textField2, textField3]
sArray2.text = sArray1

Upvotes: 1

Views: 487

Answers (2)

Bappaditya
Bappaditya

Reputation: 9652

An alternative solution with enumerated(),

let sArray1 = ["A","B","C"]
let sArray2 = [textField1, textField2, textField3]

for (index, element) in sArray2.enumerated() {
    element.text = sArray1[index]
}
print(sArray2)

Output:

[<UITextField: 0x7fd885051200; frame = (0 0; 0 0); text = 'A'; opaque = NO; layer = <CALayer: 0x6000024393e0>>, <UITextField: 0x7fd885037a00; frame = (0 0; 0 0); text = 'B'; opaque = NO; layer = <CALayer: 0x6000024394e0>>, <UITextField: 0x7fd88508f400; frame = (0 0; 0 0); text = 'C'; opaque = NO; layer = <CALayer: 0x6000024395e0>>]

Upvotes: 0

Sweeper
Sweeper

Reputation: 274650

[UITextField] does not have a text property, so you can't use sArray2.text.

You can zip and then forEach:

zip(sArray2, sArray1).forEach { $0.0.text = $0.1 }

Upvotes: 3

Related Questions