KeyPath + String

TL;DR: Swift should support turning a KeyPath into a String (e.g., .title → "title"). Devs currently use fragile hacks or macros to extract property names, but native support would simplify this significantly and aligns with SwiftData’s internal use of the feature.

1 Like

I was just walking over this thing, because at least in EOF you could traverse relationships using just the path.
E.g. say customer.addresses.city = 'Cupertino'. That would create sth like:

SELECT * FROM customer 
  LEFT JOIN address USING (address_id) 
 WHERE address.city = 'Cupertino'

I think that syntax can't work w/ Swift KeyPathes right now. Instead you are supposed to treat the relationship as a collection and do this in the predicate:

#Predicate<Customer> { $0.addresses.contains { $0.name == "Cupertino" } }

Which is much more code, but kinda reasonable from a semantic PoV.

I'm not quite sure yet what happens w/ non-optional to-one relationships though. You would think that $0.address.customer.name = 'x' would/should work. But presumably doesn't/can't?

Edit: Ah, interesting, the Predicate macro seems to split combined key pathes into direct ones. That will make all those things work.

1 Like