This is a fairly short question, but I'm a bit confused on how to fix it.
for item in filteredAndSortedDates {
print(item.datesSectionHeader()) // Returns a value
print(item.value(forKeyPath: "datesSectionHeader") as Any) // Returns nil
// The "as Any" part up above is just to keep the compiler quiet. It doesn't have any meaning as this is just for testing purposes.
}
I'm a bit confused on why this is happening. How come valueForKeyPath is returning nil
when the above is returning a value? I'm calling this on an NSDictionary
.
This is the log I'm getting:
HAPPENING THIS WEEK
nil
HAPPENING THIS WEEK
nil
HAPPENING THIS WEEK
nil
HAPPENING WITHIN A YEAR
nil
Here's how I'm declaring datesSectionHeader
:
extension NSDictionary {
// FIXME
func datesSectionHeader() -> String {
// Doing some work in here.
}
}
NSDictionary
modifies the standard behavior of Key-Value Coding so that it accesses the dictionary's contents rather than its properties. It does this by overridingvalue(forKey:)
(which is, in turn, used byvalue(forKeyPath:)
).As documented, its override of
value(forKey:)
checks if the key is prefixed by "@". If it's not, it returns the result ofobject(forKey:)
, accessing the dictionary contents. If it is prefixed with "@", it strips the "@" and returns the result from the superclass's implementation, which accesses the dictionary's properties.So, in this particular case, you can access the results from your
datesSectionHeader()
getter method using the following: