Search code examples
iosswiftswift4

How to use Swift 4 KeyPath in CAShapeLayer animation


If I write Swift 3 code it would look like this:

let animation = CABasicAnimation(keyPath: #keyPath(CAShapeLayer.path))

But I tried to use Swift 4 new syntax for keyPath and I got:

let keyPath = \CAShapeLayer.path
let animation = CABasicAnimation(keyPath: keyPath) // error line

> Error: Cannot convert value of type 'ReferenceWritableKeyPath' to expected argument type 'String?'

How can I use key path in this situation with swift 4?


Solution

  • As for now CABasicAnimation still uses the old String keyPaths so you should still use #keyPath(CAShapeLayer.path) even though you are using Swift 4.

    Apple will probably update all it's APIs in the future to make use of these safer key path references. But for now you are stuck with "unsafe" Strings.