Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created July 6, 2018 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/3790d88750a94554a699ac6ffe585386 to your computer and use it in GitHub Desktop.
Save laevandus/3790d88750a94554a699ac6ffe585386 to your computer and use it in GitHub Desktop.
func tryStoringDefaultPlanets() {
// dataStore is an instance of NSPersistentContainer subclass CoreDataStore.
guard dataStore.count(for: "Planet") == 0 else { return }
// Insert new entities into managed object context.
let names = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
let paths = ["https://en.wikipedia.org/wiki/Mercury_(planet)", "https://en.wikipedia.org/wiki/Venus", "https://en.wikipedia.org/wiki/Earth", "https://en.wikipedia.org/wiki/Mars", "https://en.wikipedia.org/wiki/Jupiter", "https://en.wikipedia.org/wiki/Saturn", "https://en.wikipedia.org/wiki/Uranus", "https://en.wikipedia.org/wiki/Neptune"]
zip(names, paths).enumerated().forEach { (offset, element) in
guard let planet = dataStore.insertNewEntity(named: "Planet") as? Planet else { return }
planet.position = Int64(offset)
planet.name = element.0
planet.url = URL(string: element.1)
}
// Save changes in the managed object context what at the moment contains added Planets.
dataStore.save()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment