@dynamic/dynamic/@NSManaged — CoreAnimation Properties in Swift
This snippet is a more detailed explanation for the use of @NSManaged with CoreAnimation properties which didn’t make the cut into:
What’s up with @NSManaged? (CoreAnimation properties in Swift)
To have a property be compatible with CoreAnimation we need the property to not be synthesized. Normally, we would use Objective-C’s @dynamic
annotation to accomplish this. However, the @dynamic
annotation in Objective-C and thedynamic
keyword in Swift are not equivalent. In Objective-C, @dynamic
prevents the compiler from synthesizing a property, while dynamic
in Swift says to always use dynamic dispatch for a particular property. (Nitin George has a good explanation of dynamic dispatch in his medium post.)
When using thedynamic
keyword on a property, Swift is still implementing the accessors, which prevents the custom property from working with Core Animation’s support. Precisely because of this, CALayer’s implicit animation API currently does not have native support for Swift — it relies heavily on the Objective-C runtime, which is no wonder that Apple’s animations are primarily written in Objective-C.
TLDR; Use @NSManaged in Swift for Animatable Properties
Though it is not the intended use of the annotation, we can use @NSManaged
to direct Swift not to synthesize accessors, allowing CoreAnimation to handle the value. This will allow our custom property to work in unison with CoreAnimation.