如何在 Swift 中将数组的所有成员初始化为相同的值?

我在斯威夫特有一个很大的阵列。我想将所有成员初始化为相同的值(也就是说,它可以是零或其他值)。最好的办法是什么?

72870 次浏览

Actually, it's quite simple with Swift. As mentioned in the Apple's doc, you can initialize an array with the same repeated value like this:

With old Swift version:

var threeDoubles = [Double](count: 3, repeatedValue: 0.0)

Since Swift 3.0:

var threeDoubles = [Double](repeating: 0.0, count: 3)

which would give:

[0.0, 0.0, 0.0]

This would be an answer in Swift 3:

var threeDoubles = [Double]( repeating: 0.0, count: 3 )