The #keyPath
directive expects an Objective-C property sequence as
argument. CALayer
inherits from NSObject
, but its position
property is struct CGPoint
, which is not a class at all, and cannot
used with Key-Value coding.
However, CALayer
has a special implementation of value(forKeyPath:)
which handles the entire key path, instead of evaluating the first key and passing down the remaining key path, compare KVC strange behavior.
So Key-Value Coding can be used with "position.x", but the
compiler does not know about this special treatment.
As an example, this all compiles and runs:
let layer = CALayer()
layer.position = CGPoint(x: 4, y: 5)
print(layer.value(forKeyPath: "position")) // Optional(NSPoint: {4, 5}
print(layer.value(forKeyPath: "position.x")) // Optional(4)
print(layer.value(forKeyPath: #keyPath(CALayer.position))) // Optional(NSPoint: {4, 5})
but this does not compile:
print(layer.value(forKeyPath: #keyPath(CALayer.position.x)))
// error: Type 'CGPoint' has no member 'x'
That is the reason why
let myAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.position.x))
does not compile, but this does (as Reinier Melian suggested):
let myAnimation = CABasicAnimation(keyPath: "position.x")