Macros for CoreData

Hi. This is primarily an observation regarding the experimental attached macros feature.
I posted a project (GitHub - daspoon/storable) which explores its use to generate CoreData object models from attributed class and property declarations. I had previously attempted the same using property wrappers, but failed to avoid incurring per-property overhead. While macros solve that essential issue, they don't allow the precise restriction on application enabled by generic overloads of property wrapper init methods.

For example, a property wrapper can distinguish to-one, to-optional or to-many relationships.

@propertyWrapper
public struct Relationship<Value> {
  init(...) where Value : NSManagedObject { ... }
  init<T: NSManagedObject>(...) where Value == T? { ... }
  init<T: NSManagedObject>(...) where Value == Set<T> { ... }
}

A corresponding macro definition can't have generic constraints on the declaration type since that type doesn't/can't appear in its signature.

@attached(accessor)
macro Relationship(...) = ...

The macro type implementation can only inspect the structure of the declaration type and must ultimately rely on type checking of expansion results to catch semantic errors.
Nonetheless, I'm very grateful for the efforts of those driving this feature forward and am excited for its future.

2 Likes