Cannot set value of type CGFloat to value of type CGFloat

I get an error when trying to set zPosition for CAShapeLayer . Here is the code:

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

For some reason I get this error: Cannot assign a value of type CGFloat to a value of type CGFloat! . For some reason, the error is related to the option. I saw other examples online without castings ( zPosition = 1 ), so I don't know what the problem is.

Thanks!

+6
source share
2 answers

The sublayers property for CALayer is defined as [AnyObject]! . When you index ...sublayers[l] , you get AnyObject , which undoubtedly does not have the zPosition property set. You need to disable the returned AnyObject before CALayer , e.g.

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

In addition, you do not need to deploy sublayers (before signing), because it is declared using ! and therefore implicitly automatically unpacked.

Finally, the error message you provided seems to have been copied incorrectly, as this is pointless.

+6
source
Undercuts

defined as an optional AnyObject array. Therefore, you need to expand the sublayers. The following should work:

 self.view.sublayers![l].zPosition = CGFloat(1) 
0
source

Source: https://habr.com/ru/post/985371/


All Articles