Swift Array(重复:,计数:)行为 [英] Swift Array(repeating:, count:) behaviour
本文介绍了Swift Array(重复:,计数:)行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 labels
数组中只有一个元素显示为 view
的子视图,特别是在使用<$时c $ c> Array(repeating :, count:)?
Why does only one element from the labels
array appear as a subview of view
, specifically when using Array(repeating:, count:)
?
let labels = Array(repeating: UILabel(), count: 7)
print(labels.count) //7
let view = UIView()
for label in labels {
view.addSubview(label)
}
print(view.subviews.count) //1
推荐答案
之所以会这样,是因为 Array(repeating:count:)
创建了一个由7个变量组成的数组,这些数组指向相同的标签。
This happens because Array(repeating:count:)
creates an array of 7 variables that are pointing to the same label.
由于所有7个元素都指向同一实例,因此子视图的计数为1。
Since all 7 elements are pointing to the same instance, the count of the subviews will be 1.
这篇关于Swift Array(重复:,计数:)行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文