2

I'm trying to rewrite an iOS project in Objective-C to Swift in Xcode 6.1 but I can't "translate" this Objective-C line :

CGFloat imageRotation = [[self.imageView valueForKeyPath:@"layer.presentationLayer.transform.rotation.z"] floatValue];

How can I get my UIImageView rotation value in Swift?

Laurent B.
  • 25
  • 4

1 Answers1

8

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382