I was able to initialise CALayer using method 1 which is properly working in the rest of code but not method 2. Could you please advise the what is wrong.
Initialise CALayer
var layers:[CALayer]!
Method 1. is working
layers = [CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer(), CALayer()]
Method 2. is not working
layers = [CALayer](count: 8, repeatedValue: CALayer())
To initialize a set with predefined list of unique elements, Swift allows to use the array literal for sets. The initial elements are comma separated and enclosed in square brackets: [element1, element2, ..., elementN] .
To create an array of specific size in Swift, use Array initialiser syntax and pass this specific size. We also need to pass the default value for these elements in the Array. The following code snippet returns an Array of size 4 with default value of 0 .
In The Swift Programming Language, it says: Functions can also take a variable number of arguments, collecting them into an array. When I call such a function with a comma-separated list of numbers (`sumOf(1, 2, 3, 4), they are made available as an array inside the function.
You can use map
and an interval:
layers = (0..<8).map { _ in CALayer() }
The _ in
is an annoyance that shouldn’t be necessary but Swift’s type inference currently needs it.
The map
approach has a big advantage over a for
-based approach, since it means you can declare layers
with let
if it isn’t going to need to change further later:
let layers = (0..<8).map { _ in CALayer() }
It may also be marginally more efficient vs multiple appends
, since the size of the array can be calculated ahead of time by map
, vs append
needing to resize the array multiple times as it grows.
Method 2 doesn't work because that initializer installs the exact same value in every index of the array.
You can use method one, or you can use a for loop:
var layers = [CALayer]()
layers.reserveCapacity(layerCount)
let layerCount = 10
for (_ in 1... layerCount)
{
layers.append(CALayer())
}
(I'm still getting used to Swift so that syntax might not be perfect, but it should give you the general idea)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With