Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access view sublayers in swift

Tags:

ios

swift

calayer

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 ?

like image 671
nelson PARRILLA Avatar asked Dec 02 '22 11:12

nelson PARRILLA


1 Answers

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
    // ...
}
like image 62
Martin R Avatar answered Dec 18 '22 10:12

Martin R