SwiftData: first steps for your iPhone app
SwiftData stores data in SwiftUI apps with just a few lines of code and can sync via iCloud. Here's how to get started.
Almost every app needs to store data: entries, settings, lists. That used to mean Core Data with a model editor and lots of boilerplate. SwiftData is Apple's modern successor, built for Swift and SwiftUI. For most new apps it's the easiest way today.
A model in three lines
A model is a plain Swift class with the @Model macro. That's all it takes:
import SwiftData
@Model
final class Thought {
var text: String
var created: Date
var topic: String
init(text: String, topic: String) {
self.text = text
self.topic = topic
self.created = .now
}
}Set up the container and show data
You set up storage once in the app. In any view you fetch data with @Query, sorted and filtered, and it updates automatically:
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ListView() }
.modelContainer(for: Thought.self)
}
}
struct ListView: View {
@Environment(\.modelContext) private var context
@Query(sort: \Thought.created, order: .reverse) private var thoughts: [Thought]
var body: some View {
List(thoughts) { Text($0.text) }
.toolbar {
Button("New") { context.insert(Thought(text: "Idea", topic: "Ideas")) }
}
}
}Saving happens automatically. You delete with context.delete and filter with the #Predicate macro, for example only thoughts of one topic.
Syncing with iCloud
Enable the iCloud capability with CloudKit and background modes in Xcode, and SwiftData syncs through the user's private iCloud. A few rules apply: every property needs a default value or must be optional, and unique attributes with @Attribute(.unique) aren't allowed. Keep that in mind from day one and you'll save yourself a painful migration later.
Tips from practice
- Previews with test data: a container with isStoredInMemoryOnly keeps previews fast and clean.
- Plan migrations: model changes use VersionedSchema and migration plans. Set them up before your first version ships.
- Not everything in one model: store large files such as photos with @Attribute(.externalStorage).
SwiftData models are observable automatically, so they behave just like classes with @Observable. More in @Observable in SwiftUI. And if your app should work entirely without an account, like Thoughts, SwiftData with iCloud is a wonderfully private solution: the data lives with the user, not on your server.