How to initialize a Swift array, for example. Calayer

I managed to initialize CALayer using method 1, which works correctly in the rest of the code, but not in method 2. Could you tell me what is wrong.

Initialize CALayer

var layers:[CALayer]!

Method 1. Works

layers = [CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer()]

Method 2. Doesn't work

layers = [CALayer](count: 8, repeatedValue: CALayer())
+4
source share
2 answers

Method 2 does not work because this initializer sets the same value at each index of the array.

You can use the one method or use the for loop:

var layers = [CALayer]()
layers.reserveCapacity(layerCount)

let layerCount = 10
for (_ in 1... layerCount)
{
  layers.append(CALayer())
}

(I'm still used to Swift, so the syntax may not be perfect, but it should give you a general idea)

+2
source

You can use the mapinterval:

layers = (0..<8).map { _ in CALayer() }

_ in - , , Swifts.

map , for, , layers let, :

let layers = (0..<8).map { _ in CALayer() }

appends, map, vs append, .

+6

All Articles