Search code examples
iosswiftcalayer

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 ?


Solution

  • 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
        // ...
    }