Swift:如何将字符串数组分配给UITextFields数组的text属性?

时间:2018-12-29 03:14:32

标签: ios arrays swift uitextfield

如果我有2个字符串数组,那么在一行代码中将一个分配给另一个很简单(无需使用for循环):

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

但是,我想对UITextFields数组执行类似的操作,但是无法弄清楚。我觉得应该看起来像这样:

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

2 个答案:

答案 0 :(得分:3)

[UITextField]没有text属性,因此您不能使用sArray2.text

您可以先zip,然后再forEach

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

答案 1 :(得分:0)

使用enumerated()的替代解决方案,

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

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

输出:

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