1

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

2 Answers 2

3

[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 }
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean that [UITextField] doesn't have a text property? I write things like nameOfTextField.text = "something" all the time. Or are you specifically referring to an array of UITextFields not having that property? It seems like there should be a way to .map the strings to each of the fields in the field array...
@Kayan Array does not have a text property, even though its elements do. You could map the textfields to their text properties, but then you can't set their texts. Because you want to change the textfield's state, so you should use forEach.
0

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>>]

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.