nelson PARRILLA
nelson PARRILLA

Reputation: 703

How to access view sublayers in swift

I would like to access view sublayers in swift 4.1 by writting :

for layer : CALayer in myView.layer.sublayers {
         // Code
}

but get the error :

Type '[CALayer]?' does not conform to protocol 'Sequence'

Does that mean that CALayer is unreachable by for loop ?

Upvotes: 6

Views: 4910

Answers (1)

Martin R
Martin R

Reputation: 539915

The sublayers property is an optional array (and by default nil). You have to unwrap it first, e.g. with optional binding:

if let sublayers = myView.layer.sublayers {
    for layer in sublayers {
        // ...
    }
}

Alternatively with optional chaining and forEach:

myView.layer.sublayers?.forEach { layer in
    // ...
}

Upvotes: 19

Related Questions