In a view controller in my app, I'm reacting to changes to a view's positioning by key-value observing its center
property, like this:
class CoordinatingViewController: UIViewController {
@IBOutlet weak var cardContainerView: CardView!
override func viewDidLoad() {
super.viewDidLoad()
addObserver(self, forKeyPath: "cardContainerView.center", options: [.new], context: nil)
}
}
This works just fine for now, but since that key path is a string, it can't be checked by the compiler. To mitigate this, I'd like to use Swift 3's #keyPath()
syntax, which takes a compiler-checked key path and returns the proper corresponding string. However, when I change that line to use it like this:
addObserver(self, forKeyPath: #keyPath(cardContainerView.center), options: [.new], context: nil)
The compiler gives me 2 errors:
- Type 'CardView!' has no member 'center'
- Cannot refer to type member 'center' within instance of type 'CardView!'
I don't understand why I'm getting these errors, as center
is a documented property of UIView
, which CardView
inherits from directly, which I can both read and write to outside the #keyPath()
statement there. Furthermore, everything appears to work ok when I pass the key path directly as a string, as in my first example, which makes this even more confusing. How can I have the compiler check that key path for me?