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

299 Views Asked by At

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?

1

There are 1 best solutions below

3
Shehata Gamal On BEST ANSWER

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/