Search code examples
swiftcastingcalayer

Cannot assign a value of type CGFloat to a value of type CGFloat


I'm getting an error when trying to set the zPosition of a CAShapeLayer. Here's the code:

self.view.layer.sublayers[l].zPosition = CGFloat(1)

For some reason I'm getting this error: Cannot assign a value of type CGFloat to a value of type CGFloat!. For some reason, the error is with the optional. I've seen other examples online done without any casting (zPosition = 1), so I don't know what the issue is here.

Thanks!


Solution

  • The sublayers property of a CALayer is defined as [AnyObject]!. When you subscript as ...sublayers[l] you are getting an AnyObject which, to be sure, does not have a settable property of zPosition. You need to downcast the returned AnyObject to a CALayer with, for example

    if let layer = self.view.layer.sublayers[l] as? CALayer {
      layer.zPosition = CGFloat(1)
    }
    

    Also, you don't need to unwrap sublayers (before subscripting) because it is declared with ! and is thus implicitly, automatically unwrapped.

    Finally, the error message you quoted appears to be mis-copied as it is nonsensical.