为什么在Swift中这样初始化数组是错误的?

Why it's wrong to init array in this way in Swift?

我将以这种方式初始化一个包含 6 个 UIImageView 的数组:

var imageViews = [UIImageView](repeating: UIImageView(), count: 6)

但是我发现里面的每一个元素都有相同的地址。如果我更改一个 imageView,我将更改所有这些。

我不知道它是如何工作的,我应该怎么做才能将它们分开?

这就是它的工作原理。

如果您检查 documentation,它表示:

Creates a new collection containing the specified number of a single, repeated value.

如果您想要单独的值,请明确创建它们

var imageViews = [UIImageView(), UIImageView(), UIImageView(), ...]

或者使用循环。但如果发生意外情况,请务必检查文档,因为您要么在 SDK 中发现错误,要么在您自己的假设中发现错误。