Search code examples
swiftdirectivekvc

What is the use of #keyPath rather than directly passing key as a String?


What is the useful difference between these two formats:

request.sortDescriptors = [NSSortDescriptor(key:"dateCreated", ascending: false)]

and

request.sortDescriptors = [NSSortDescriptor(key: #keyPath(Note.dateCreated), ascending: false)]

In the second format #keyPath is confusing to me. What exactly it is and where I can read more about this?


Solution

  • There is no difference between

    key:"dateCreated"
    

    and

    key: #keyPath(Note.dateCreated)
    

    both will do the sort with Note object's dateCreated property the latter has an advantage of avoiding hard coding problems e.x writing datCreated instead of dateCreated will throw a compile time error , so it'll safely avoid run-time crashes that definitely will happen with the former under same circumstances

    https://www.klundberg.com/blog/swift-4-keypaths-and-you/

    http://chris.eidhof.nl/post/sort-descriptors-in-swift/