SwiftData: Simplifying Persistence in iOS Apps


It’s the daybreak of a brand new day for coping with persisting information in your iOS apps.

SwiftData is right here.

OK, hyperbole apart, customers of Core Knowledge have waited for SwiftData for a lengthy time. What’s SwiftData, and why must you care?

What Is SwiftData?

Earlier than diving into a number of the particulars of SwiftData, that you must know what it’s. SwiftData was launched at WWDC 2023 and is a framework that gives a Swift-like API for working with persistence in your app. You may even say it’s “Swift native”.

An essential distinction to make right here is that SwiftData nonetheless makes use of the underlying storage structure of Core Knowledge. SwiftData merely presents a extra user-friendly syntax for working with Core Knowledge.

Truly, “merely” is a poor alternative of phrases. In case you’ve labored with Core Knowledge previously, you’ll discover SwiftData’s new syntax merely wonderful.

To grasp why it’s so wonderful, a small look again is required.

A Temporary Look Again

Ever since Swift got here out, utilizing Core Knowledge together with your app has all the time appeared misplaced. The entire “Swift-y” options that got here out every year with Swift and SwiftUI had been leaving Core Knowledge, which had a deep Goal C heritage, within the mud.

A superb instance right here is the .xcdatamodeld, or Schema Mannequin Editor, file. This file is used to outline your database’s schema.

The Schema Model Editor

This can be a handy method to outline all the weather of your mannequin, however it feels separate from the remainder of your code. In reality, the compiler makes use of the schema to make class information for you, however they’re positioned within the derived information of your challenge! This system additionally differs from the strategy taken in SwiftUI, which pushes builders towards defining the whole lot in code as a substitute of separate helper information like storyboards.

Incremental Adjustments

This isn’t to say that Apple was ignoring Core Knowledge. Every WWDC would see some welcome enhancements to the framework. The creation of the NSPersistentCloudKitContainer encapsulated a big chunk of code that builders usually needed to write themselves to maintain their Core Knowledge and CloudKit shops in sync. The introduction of property wrappers reminiscent of @FetchRequest and @SectionedFetchRequest helped hold SwiftUI views in sync with the database similar to a traditional @State/@Binding pair. In reality, property wrappers gave lots of people hope that one thing may very well be performed to make Core Knowledge a bit extra “Swift-y”.

Then Swift 5.9 was launched.

Swift Macros and Swift Knowledge

The introduction of Swift macros in Swift 5.9 appears prefer it’ll be a sport changer. There’s certain to be lots of content material right here at Kodeco to cowl Swift macros within the close to future, so for now, listed here are a number of the highlights whereas trying out SwiftData.

Right here’s a mannequin for a Recipe class:

class Recipe {
    var identify: String
    var abstract: String?
    var elements: [Ingredient]
}

If I had been utilizing Core Knowledge, I’d have to enter the Schema Editor, add a brand new entity, and add attributes for the properties. With SwiftData, that’s all performed with one addition, @Mannequin:

import SwiftData

@Mannequin
class Recipe {
    var identify: String
    var abstract: String?
    var elements: [Ingredient]
}

That’s it! Our Recipe class is now a sound mannequin to be used in SwiftData, which has its personal import while you wish to use it. However what precisely is @Mannequin? Proper-clicking on @Macro and selecting Increase Macro exhibits precisely what this macro has added to your class:

The expanded @Model macro

That’s lots of added code! The @Mannequin macro units up a wonderfully legitimate mannequin, however you can even make customizations. For instance, to make sure the identify is exclusive, you’ll be able to add a macro to that property:

@Mannequin
class Recipe {
    @Attribute(.distinctive) var identify: String
    var abstract: String?
    var elements: [Ingredient]
}

You may even outline deletion guidelines for the relationships utilizing the @Relationship macro:

@Mannequin
class Recipe {
    @Attribute(.distinctive) var identify: String
    var abstract: String?

    @Relationship(.cascade)
    var elements: [Ingredient]
}

Associating the Mannequin With Your App

Gone are the times of the Persistence.swift file for initializing the persistence stack in your app. SwiftData has a brand new modifier that allows you to outline precisely which sorts you wish to take into account a part of your mannequin:

@foremost
struct RecipeApp: App {

    var physique: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(for: [Recipe.self, Ingredient.self])
    }
}

The modelContainer(for:) modifier takes an array of sorts you need your mannequin to trace.

That’s it! There’s no step 2! However what about accessing the info?

Accessing Knowledge

With a mannequin outlined and the modelContainer injected into the setting, you’ll be able to entry your database entries!

@Question var recipes: [Recipe]
var physique: some View {
    Checklist(recipes) { recipe in
        NavigationLink(recipe.identify, vacation spot: RecipeView(recipe))
    }
}

That’s it! There’s nonetheless no step 2! You may, nonetheless, customise the question to deal with issues like sorting:

@Question(kind: Recipe.identify, order: .ahead) 
var recipes: [Recipe]

var physique: some View {
    Checklist(recipes) { recipe in
        NavigationLink(recipe.identify, vacation spot: RecipeView(recipe))
    }
}

Inserting and Deleting Knowledge

To insert and delete information from the datastore in Core Knowledge, you wanted entry to the shop’s context. The identical is true for SwiftData. Once you arrange the .modelContainer earlier, that additionally arrange a default mannequin context and injected it into the setting. This enables all SwiftUI views within the hierarchy to entry it by way of the .modelContext key path within the setting.

After you have that, you need to use context.insert() and context.delete() calls to insert and delete objects from the context.

struct RecipesView: View
{
  @Surroundings(.modelContext) non-public var modelContext

  @Question(kind: Recipe.identify, order: .ahead) 
  var recipes: [Recipe]

  var physique: some View {
    NavigationView {
      Checklist {
        ForEach(recipes) { recipe in
          NavigationLink(recipe.identify, vacation spot: RecipeView(recipe))
        }
        .onDelete(carry out: deleteRecipes)
      }
    }
    .toolbar {
      ToolbarItem(placement: .navigationBarTrailing) {
        EditButton()
      }
      ToolbarItem {
        Button(motion: addRecipe) {
          Label("Add Recipe", systemImage: "plus")
        }
      }
    }
  }

  non-public func addRecipe() {
    withAnimation {
      let newRecipe = Recipe("New Recipe")
        modelContext.insert(newRecipe)
    }
  }

  non-public func deleteRecipes(offsets: IndexSet) {
    withAnimation {
      for index in offsets {
        modelContext.delete(recipes[index])
      }
    }
  }
}

In case you’ve used Core Knowledge previously, you might have observed there’s no name to context.save(). That’s proper — as a result of it’s not required. By default, SwiftData will autosave your context to the shop on a state change within the UI or after a sure time interval. You’re free to name save() if you want, although.

Simply Scratching the Floor

SwiftData has launched a a lot less complicated method to persist your information in your Swift apps. Because of Swift macros, you’ll be able to immediately make your fashions, in code, SwiftData prepared and configure them to your liking. With a brand new modifier, you’ll be able to entry the context, and with the brand new @Question property wrapper, you’ll be able to simply carry out queries. Oh, did I point out that the @Question property wrapper is all arrange for Statement, so your person interface stays updated with the database? There’s loads packed into slightly little bit of configurable syntax beneath the hood. Hold a watch out right here at Kodeco for extra on one of many greatest modifications to return out of WWDC 2023!

The place to Go From Right here?

WWDC has an awesome set of movies to get an introduction to SwiftData:

We hope you loved this fast have a look at SwiftData, and when you’ve got any questions or feedback, please be part of the discussion board dialogue beneath!

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles