title: How to add Core Data to existing Xcode 9 Swift 4 iOS 11 project?
body: <p>An update is requested, since this question has of course been answered for previous versions, the latest search result dated 12/16 generates irrelevant compatibility with previous iOS 9 and 10 projects.</p>
  
  <p>The documentation of course says to select the Use Core Data checkbox when starting a new project, which I did not select, but now think iCloud + Core Data needs to be added to take my app to its next phase -> wherein something like NSFileCoordinator and NSFilePresenter is needed, since in my app UI users are presented with a number of TOPICS, each having three OPTIONS, regarding which users are to choose one option. For each topic the UI then displays the TOTAL NUMBER of users who have chosen each option and the PERCENTAGE of the total for each option. </p>
  
  <p>Right now, the number of choices for each option and the percentage of the total are of course just calculated in my native app -> but actually need to be CALCULATED in something central like the cloud or most likely on a website…but then the website raises the simultaneous read/write problems that NSFileCoordinator and NSFilePresenter have already solved.</p>
  
  <p>So if the iCloud + Core Data system can interject basic arithmetic calculations on the existing Ubiquitous Container numerical value totals - in the cloud upon receiving write numerical value commands from individual users - before sending out the new Ubiquitous Container numerical total and percent values - then I’d much appreciate advise on how fix the errors generated below in trying Create and Initialize the Core Data Stack. Otherwise guess I’ll have to scrape Xcode and go to a hybrid app like PhoneGap if that's the best one for the job.</p>
  
  <p>Hence, referring to the Core Data Programming Guide:</p>
  
  <p><a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1" rel="noreferrer">https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1</a></p>
  
  <p>and pasting in the following code in the beginning of my existing project, generates </p>
  
  <blockquote>
    <p>Use of unresolved identifier ‘persistentContainer’… ‘managedObjectContext’</p>
  </blockquote>
  
  <p>... errors. And the line</p>
  
  <pre><code>init(completionClosure: @escaping () -&gt; ()) { 
  </code></pre>
  
  <p>... generates </p>
  
  <blockquote>
    <p>Initializers may only be declared within a type</p>
  </blockquote>
  
  <pre><code>import UIKit
  
  import CoreData
  class DataController: NSObject {
    var managedObjectContext: NSManagedObjectContext
    init(completionClosure: @escaping () -&gt; ()) {
      persistentContainer = NSPersistentContainer(name: "DataModel")
      persistentContainer.loadPersistentStores() { (description, error) in
        if let error = error {
          fatalError("Failed to load Core Data stack: \(error)")
        }
        completionClosure()
      }
    }
  }
  
  init(completionClosure: @escaping () -&gt; ()) {
    //This resource is the same name as your xcdatamodeld contained in your project
    guard let modelURL = Bundle.main.url(forResource: "DataModel", withExtension:"momd") else {
      fatalError("Error loading model from bundle")
    }
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
      fatalError("Error initializing mom from: \(modelURL)")
    }
  
    let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
  
    managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = psc
  
    let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
    queue.async {
      guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
        fatalError("Unable to resolve document directory")
      }
      let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
      do {
        try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
        //The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from.
        DispatchQueue.main.sync(execute: completionClosure)
      } catch {
        fatalError("Error migrating store: \(error)")
      }
    }
  }
  
  // followed by my existing working code:
  
  class ViewController: UIViewController {
  </code></pre>