Dan Beaulieu Dan Beaulieu - 1 year ago 75
Swift Question

Use the inout keyword when passing an NSManagedObjectContext into a function?

I'm working on my first real Core Data application and have been able to successfully pass the pointer to my

instance throughout my application using segues. I've run into a question however as I am at a crossroad where I need to pass my
into a function.


Since functions are pass-by-value by default, I'm assuming that I'd be making a copy of my managedObjectContext instance thus potentially defeating the purpose of passing the original pointer to my managedObjectContext instance.

Should I use the
modifier to avoid creating copies of my managedObjectContext?

Answer Source

NSManagedObjectContext is a class, and therefore a reference type. Reference types do not need to be passed with inout to share the instance. The "value" that is passed for reference types is the pointer to them.

One thing that was lost (IMO) in the transition from ObjC to Swift is that reference types no longer have any indicator. In ObjC, you could identify them by the * in their type. In Swift, you just have to know which are which.