It is only slightly more complex in Swift because valueForKeyPath
returns
an optional which has to be unwrapped an then explicitly cast to NSNumber
.
This can (for example) be done with a combination of optional chaining
and optional cast:
let zKeyPath = "layer.presentationLayer.transform.rotation.z"
let imageRotation = (self.imageView.valueForKeyPath(zKeyPath) as? NSNumber)?.floatValue ?? 0.0
The final "nil-coalescing operator" ??
sets the value to 0.0
if the key path is not
set (or is not an NSNumber
), this mimics the behaviour of Objective-C where
sending the floatValue
message to nil
would also return 0.0
.