Contents.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //: To get this Playground running do the following:
  2. //:
  3. //: 1) In the scheme selector choose RealmSwift > iPhone 6s
  4. //: 2) Press Cmd + B
  5. //: 3) If the Playground didn't already run press the ▶︎ button at the bottom
  6. import Foundation
  7. import RealmSwift
  8. //: I. Define the data entities
  9. class Person: Object {
  10. dynamic var name = ""
  11. dynamic var age = 0
  12. dynamic var spouse: Person?
  13. let cars = List<Car>()
  14. override var description: String { return "Person {\(name), \(age), \(spouse?.name)}" }
  15. }
  16. class Car: Object {
  17. dynamic var brand = ""
  18. dynamic var name: String?
  19. dynamic var year = 0
  20. override var description: String { return "Car {\(brand), \(name), \(year)}" }
  21. }
  22. //: II. Init the realm file
  23. let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "TemporaryRealm"))
  24. //: III. Create the objects
  25. let car1 = Car(value: ["brand": "BMW", "year": 1980])
  26. let car2 = Car()
  27. car2.brand = "DeLorean"
  28. car2.name = "Outatime"
  29. car2.year = 1981
  30. // people
  31. let wife = Person()
  32. wife.name = "Jennifer"
  33. wife.cars.append(objectsIn: [car1, car2])
  34. wife.age = 47
  35. let husband = Person(value: [
  36. "name": "Marty",
  37. "age": 47,
  38. "spouse": wife
  39. ])
  40. wife.spouse = husband
  41. //: IV. Write objects to the realm
  42. try! realm.write {
  43. realm.add(husband)
  44. }
  45. //: V. Read objects back from the realm
  46. let favorites = ["Jennifer"]
  47. let favoritePeopleWithSpousesAndCars = realm.objects(Person.self)
  48. .filter("cars.@count > 1 && spouse != nil && name IN %@", favorites)
  49. .sorted(byProperty: "age")
  50. for person in favoritePeopleWithSpousesAndCars {
  51. person.name
  52. person.age
  53. guard let car = person.cars.first else {
  54. continue
  55. }
  56. car.name
  57. car.brand
  58. //: VI. Update objects
  59. try! realm.write {
  60. car.year += 1
  61. }
  62. car.year
  63. }
  64. //: VII. Delete objects
  65. try! realm.write {
  66. realm.deleteAll()
  67. }
  68. realm.objects(Person.self).count
  69. //: Thanks! To learn more about Realm go to https://realm.io