Guardian667
Guardian667

Reputation: 452

Swift: Class parameter as default function parameter

I'm trying to define a default function parameter in Swift. By default a reference within this class should be used (function loadMyEntities(...)). Xcode (v6 Beta 4) displays Use of unresolved Identifier 'self'. Using only context, instead of self.context causes the error 'DB.Type' does not have a member named 'context'. How can I handle this, to use "values behind references" as default parameters.

In my specific case, core data should load entities in an extra created NSManagedObjectContext or in a default context otherwise.

class DB {
  var appDelegate: AppDelegate
  var context: NSManagedObjectContext
  var persistenceCoordinater: NSPersistentStoreCoordinator

  init() {
    self.appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    self.context = appDelegate.managedObjectContext!
    self.persistenceCoordinater = context.persistentStoreCoordinator
  }

  // !!! Here's the point where I want to use the DB objects context as default !!!
  func loadMyEntities(context: NSManagedObjectContext = self.context) -> [MyEntity] {
    // loading entities
  }

  // This function can be used 
  func createContext() -> NSManagedObjectContext {
    var newContext = NSManagedObjectContext()
    newContext.persistentStoreCoordinator = self.persistenceCoordinater
    return newContext
  }
}

A workaround would be defining the function twice, once with the parameter, once without, and delegate from the one without a given context.

func loadMyEntities() -> [MyEntity] {
  return loadMyEntities(self.context)
}

func loadMyEntities(context: NSManagedObjectContext) -> [MyEntity] {
    // loading entities
}

But that's not pretty nice ;-)

My question targets on parameter usage if swift, but comments for encapsulating core data in this way are also welcome.

Upvotes: 0

Views: 564

Answers (1)

Rob Napier
Rob Napier

Reputation: 299455

But that's not pretty nice ;-)

There's nothing wrong with the overloading approach. It's very clear and flexible. That's what overloads are for. I've encountered this numerous times so far, and keep being reminded that over-complicated defaults are the wrong solution. Swift has overloads for a reason. They solve exactly the problem here.

Remember, default parameters are just a shortcut for expressing an overload. There are limits on how far you can push a shortcut.


EDIT: In this particular case, the natural solution would be to convert the parameter to an optional (which is exactly what you mean; it's optional).

func loadMyEntities(context: NSManagedObjectContext? = nil) -> [MyEntity] {
    if let context = context ?? self.context {
        ...
    }
}

Upvotes: 2

Related Questions