Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do I initialise Swift array of object eg. CALayer

Tags:

swift

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())
like image 610
digidhamu Avatar asked Apr 12 '15 11:04

digidhamu


People also ask

How do you initiate an array in Swift?

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] .

How do I declare a fixed size array in Swift?

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 .

How do you pass an array to a function in Swift?

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.


2 Answers

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.

like image 197
Airspeed Velocity Avatar answered Oct 11 '22 19:10

Airspeed Velocity


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)

like image 33
Duncan C Avatar answered Oct 11 '22 19:10

Duncan C