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

10,186

Solution 1

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.

Solution 2

sublayers is defined as an Optional array of AnyObject's. Therefore you have to unwrap sublayers. The following should work:

self.view.sublayers![l].zPosition = CGFloat(1)
Share:
10,186
Admin
Author by

Admin

Updated on June 16, 2022

Comments

  • Admin
    Admin almost 2 years

    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!

  • Admin
    Admin about 9 years
    Whoops, mis-copied. I fixed it.
  • vguerra
    vguerra about 9 years
    yes.. you are right.. sorry for that one. @GoZoner got it right =)
  • Admin
    Admin about 9 years
    No worries! Thanks for taking the time to answer.