포스트

[WWDC26] Code-along: Add persistence with SwiftData

이 글은 WWDC 세션의 transcript 와 영상 화면을 Claude Code 로 정리한 글이고, 실제로 쓴 날은 2026-11-24 다. code 는 세션 page 의 snippet 에 빠진 type 과 init 을 채워 Swift package (macOS 27, Swift 6.4, Swift 6 language mode) 로 build 했다.


세션 정보

  • 세션: Code-along: Add persistence with SwiftData
  • 길이: 22분 35초
  • 공개일: 2026-06-08
  • 발표: Matthew Turk (SwiftData team)
  • 코드: 세션 page 에 snippet 10개. 세션은 sample app 을 developer.apple.com 에서 받을 수 있다고 안내한다.

한 줄 요약

memory 에만 있던 SwiftUI 앱의 data 를 @Model 로 바꾸고, relationship 으로 잇고, view 마다 필요한 만큼만 가져오는 @Query 로 바꾸면 저장과 갱신이 따라온다.


세션의 구성

세션은 Wishlist 라는 list 기반 앱의 source 에서 시작한다. 여행 아이디어를 적고 계절별 collection 으로 묶는 앱이다. 여기에 SwiftData 를 넣는 과정을 네 단계로 따라간다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

  • Identify relevant state: 저장해야 할 state 찾기
  • Define your schemas: model 과 schema 정의
  • Define model relationships: model 사이의 관계 정의
  • Update the view layer: SwiftUI view 를 새 model 에 맞추기

저장할 state 찾기

먼저 앱이 지금 data 를 어떻게 흘려보내는지 본다.


Wishlist 앱의 화면

앱에는 tab 이 셋 있다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

  • Wishlist tab: 위에 최근 trip, 아래로 주제별 trip 목록
  • Goals tab: trip 에서 이루고 싶은 goal 의 badge
  • Search tab: trip 과 activity 검색

발표자는 trip 하나를 검색해서 activity 를 완료로 표시하고, Wishlist tab 에서 “Northern Lights” 라는 새 trip 을 사진과 함께 더한다.


memory 에만 있는 DataSource

이 흐름은 view 들이 SwiftUI environment 에서 DataSource 를 꺼내 쓰기 때문에 돌아간다. DataSource class 가 미리 넣어 둔 trip data 를 모두 들고 있고, trip, goal, 검색 결과는 필요할 때마다 memory 에서 걸러지고 정렬된다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

작은 예제에서는 괜찮다. 하지만 실제로는 화면 쪽을 가볍게 유지하려면 최적화가 필요해진다. 그리고 처리도 저장도 RAM 에 기대고 있어서, 새 trip 이나 activity 를 나중까지 남겨 둘 수 없다. 앱을 닫았다가 다시 실행하면 방금 만든 trip 은 사라지고 처음 content 로 돌아간다.

SwiftData 가 푸는 문제가 바로 이것이다. 찾아낸 state 는 trip collection, goal 의 상태, 검색 결과 셋이고, SwiftData 는 이 state 를 model context 를 통해 저장소에 잇는다. 세션이 끝날 때의 모습은 다음과 같다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

DataSource 자리에 ModelContext, @Environment 자리에 @Query, RAM 자리에 database 가 들어간다.


schema 정의

다음은 data 구조를 찾아 SwiftData model 로 바꾸는 일이다.


Activity 를 model 로 바꾸기

Activity 를 저장하려면 SwiftData 를 import 하고 @Observable macro 를 @Model 로 바꾼다. Observable conformance 는 SwiftData 가 만들어 준다.

원래 code 에는 name 과 isComplete 에 didSet 이 달려 있었다. 둘 중 하나가 바뀌면 dateEdited 를 현재 시각으로 고치는 observer 다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

세션은 이것을 timeline 으로 보여 준다. paragliding 이던 activity 의 이름을 swimming 으로 바꾸면 name 의 observer 가 불려 dateEdited 가 바뀌고, 나중에 완료로 표시하면 isComplete 의 observer 가 불려 다시 바뀐다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

저절로 갱신되는 dateEdited 는 list 를 정렬하거나 거르기에 좋다. 하지만 property observer 와 computed property 는 늘 함께 쓸 수 있는 것이 아니다. @Model 은 stored property 를 computed property 로 바꾸는 macro 이므로 didSet 을 둘 수 없다는 뜻으로 읽었다. 이 설명은 세션에 없고 내 해석이다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

그래서 지금은 didSet block 을 지우고 dateEdited 는 그대로 둔다. 갱신은 뒤에서 다른 방법으로 되살린다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Foundation
import SwiftData
import Observation

@Model
class Activity {
    var name: String
    var isComplete: Bool = false
    var dateCreated = Date.now
    var dateEdited = Date.now
    var trip: Trip?
    @Transient var token: ObservationTracking.Token?

    init(name: String) { self.name = name }
}

snippet 에는 앞의 property 넷만 있다. trip, token, init 은 뒤의 snippet 들이 쓰기 때문에 내가 더했다. token 은 저장할 값이 아니므로 @Transient 를 붙였다.

Model macro

Model() 은 class 를 SwiftData 가 저장하는 model 로 바꾸는 macro 다. PersistentModel 과 Observable conformance 를 함께 만든다.

Transient macro

Transient() 은 model 의 property 를 저장 대상에서 빼는 macro 다. 세션에는 나오지 않는다.


Trip 의 build error 고치기

Trip class 도 같은 식으로 import 를 더하고 macro 를 바꾼다. 그러면 build 가 실패한다. 세션은 error 를 하나씩 읽으며 무엇이 빠졌는지 찾는다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

첫 error 는 creationDate 가 mutable 이어야 한다는 것이다. let 을 var 로 바꾼다. 그래야 SwiftData 가 runtime 에 database 에서 읽은 값을 이 property 에 채울 수 있다.

다음 error 는 TripCollection property 를 비롯한 모든 model property 가 Codable 이어야 한다는 것이다. SwiftData 가 property 를 database 의 column 으로 serialize 하려면 필요한 조건이다. TripCollection 은 trip 의 계절 주제를 담는 enum 이고 schema 에 들어가야 하므로, 선언으로 가서 Codable 을 더한다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
enum TripCollection: String, CaseIterable, RawRepresentable, Codable {
    case springEscapes
    case summerVibes
    case fallGetaways
    case winterRetreats
}

error 가 아직 남아 있지만 schema 를 채워 가면서 고친다.


enum 이던 Goal 을 class 로

Goal 은 @Observable 을 @Model 로 바꾸는 것으로 끝나지 않는다. enum 으로 선언되어 있기 때문이다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

goal 마다 이름, kind (activity 완료를 세는지 trip 완료를 세는지), 달성에 필요한 target 수가 있다. goal 은 정확히 18개이고 모두 미리 정해져 있다. enum 은 닫힌 값의 집합을 정의하기 때문이다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

처음의 화면 demo 에는 충분했지만 저장되는 model 에는 class 가 필요하다. class 는 property 를 저장할 수 있고 몇 번이든 instance 를 만들 수 있다.

goal 하나는 조건이 채워졌는지에 따라 앱에 표시되는 badge 하나에 대응한다. goal 의 상태를 제대로 저장하려면 그 조건이 채워졌는지를 담는 가장 작은 표현이 필요하다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

발표자는 Goal 을 class 로 바꾸면서 먼저 같은 property 셋을 둔다. 원래 앱은 완료한 수를 따로 저장했다. enum 에는 stored property 가 없기 때문이다. 이제 class 이므로 진행 값을 goal 안에 completedCount 로 두고, isComplete 라는 Bool 도 둔다. completedCount 가 target 이상이면 true 를 저장한다. stored property 이므로 view 에서 query 할 때 달성한 goal 과 남은 goal 을 가르는 데 쓸 수 있다.

출처: WWDC26 - Code-along: Add persistence with SwiftData


kind 를 inheritance 로 나누기

남은 것은 kind 다. 앱은 goal 이 trip 완료에 관한 것인지 activity 완료에 관한 것인지에 따라 다른 내용을 보여 준다. 세션은 이 차이를 SwiftData 의 model inheritance 로 subclass 에 떼어 낸다.

inheritance 는 class 의 위계가 잘 정해져 있을 때 효과가 난다. subclass 가 superclass 와 같은 개념이면서 공통 property 를 더 구체적으로 드러낼 때다. 세션은 나선 은하와 렌즈형 은하를 예로 든다. 둘 다 별과 먼지처럼 어느 은하에나 있는 것을 물려받고, 보이는 모양에서 갈린다. 마찬가지로 trip goal 과 activity goal 이 Goal 의 공통 property 를 물려받게 한다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

Goal 에서 kind 를 빼고 TripGoal 과 ActivityGoal subclass 를 만든다. model inheritance 를 언제 쓰는 것이 맞는지는 SwiftData: Dive into inheritance and schema migration (WWDC25) 에서 다룬다.

세션 page 에는 Goal 의 snippet 이 없다. 뒤의 query 가 쓰는 property 에 맞춰 내가 쓴 code 는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Model
class Goal {
    var name: String
    var target: Int
    var completedCount: Int = 0
    var isAchieved: Bool = false
    var dateAchieved: Date?
    var sortOrder: Int = 0

    init(name: String, target: Int) {
        self.name = name
        self.target = target
    }
}

@available(macOS 27, iOS 27, *)
@Model
final class TripGoal: Goal {
    var collection: TripCollection?

    init(name: String, target: Int, collection: TripCollection?) {
        self.collection = collection
        super.init(name: name, target: target)
    }
}

두 가지를 알아 둔다.

  • 영상의 그림은 isComplete 라고 쓰지만 세션 page 의 query snippet 은 isAchieved, dateAchieved, sortOrder 를 쓴다. snippet 쪽 이름을 따랐다.
  • subclass 에 @available 이 없으면 @Model macro 가 platform availability 를 명시하라는 error 를 낸다. 그래서 붙였다. 세션은 이 점을 말하지 않는다.
  • 이 model 을 macOS 27.0.1 에서 file 에 저장하고 다시 읽으면, FetchDescriptor<Goal> 로 가져와 as? TripGoal 로 cast 한 object 의 collection 이 nil 로 읽힌다. 저장된 값은 온전하고, 같은 context 에서 FetchDescriptor<TripGoal> 로 한 번 fetch 하면 그 뒤로는 값이 나온다. subclass 의 property 를 쓰는 화면은 subclass type 으로 query 한다.

model 사이의 relationship

model 이 모였으니 서로를 잇는다.


dictionary 대신 to-many relationship

Wishlist 에서 trip 하나에는 activity 여럿이 딸린다. to-many relationship 이다. 원래 앱은 이것을 dictionary 와 배열을 도는 함수로 흉내 냈다. activity ID 로 trip 에서 activity 를 찾는 dictionary 가 그런 예다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

이것을 type 사이의 진짜 relationship 으로 바꾼다. trip 하나가 activity 를 0개 이상 가진다. SwiftData 에서는 배열을 선언하는 것이 한 model 이 다른 model 을 참조한다고 알리는 방법이다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

Trip 에 activities 배열을 선언하고 @Relationship macro 를 붙인다. trip 을 지우면 그 일정에 있던 activity 도 함께 지워지게 하려는 것이다.

출처: WWDC26 - Code-along: Add persistence with SwiftData


사진을 thumbnail 과 외부 저장으로 나누기

photoURL 도 손봐야 한다. 지금은 file path 일 뿐이라서 file 이름이 바뀌거나 다른 directory 로 옮겨지면 의미를 잃는다. 그리고 원본 해상도의 image 는 TripDetailView 처럼 크게 보여 줄 때만 읽으면 된다. trip 을 넘겨 보는 carousel 에서는 thumbnail 이면 충분하다.

그래서 둘로 나눈다.

  • thumbnailData: 고른 사진의 저해상도 version 을 database 안에 byte 로 넣어 둔다.
  • 원본 image: URL 대신 persistent external file reference 로 저장한다. SwiftData 에서는 image 만 담는 model 을 따로 만들어서 한다. 세션은 TripImage 를 미리 만들어 두었고 구현은 sample code 를 읽으라고 한다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

photoURL 은 이제 URL 이 아니므로 photo 로 이름을 바꾼다. 선언을 오른쪽 click 해서 refactor menu 의 Rename 을 고르면 여러 file 이 한꺼번에 바뀐다. comment 안의 이름도 click 해서 함께 바꾼다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

이어서 initializer 의 label 을 고치고, 본문에서 dictionary 를 만들던 줄을 activities 를 그대로 대입하는 줄로 바꾼다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Model
class Trip {
    var name: String
    var collection: TripCollection

    var photo: TripImage
    var thumbnailData: Data?

    @Relationship(deleteRule: .cascade, inverse: \Activity.trip)
    var activities: [Activity] = []

    private(set) var creationDate = Date.now
    var subtitle: String?
    var isComplete: Bool = false

    init(name: String, collection: TripCollection, photo: TripImage,
         activities: [Activity] = [], subtitle: String? = nil) {
        self.name = name
        self.collection = collection
        self.photo = photo
        self.activities = activities
        self.subtitle = subtitle
    }
}

@Model
class TripImage {
    @Attribute(.externalStorage) var data: Data?
    init(data: Data? = nil) { self.data = data }
}

snippet 에는 init 이 없어서 영상 화면의 것을 옮겼다. TripImage 는 세션이 구현을 보여 주지 않으므로 externalStorage attribute 를 쓴 가장 단순한 모양으로 내가 썼다.

relationship 을 맺으면 activity 를 보여 주는 view 가 부모 trip 의 이름, 계절 같은 내용을 참조하던 예전 기능이 그대로 살아난다.

Relationship macro

Relationship 은 property 를 model 사이의 관계로 표시하는 macro 다. deleteRule: .cascade 는 이 model 이 지워질 때 관계된 model 도 지우고, inverse 는 반대쪽 property 를 가리킨다.

externalStorage option

externalStorage 는 property 의 값을 model 의 다른 data 옆 binary file 로 저장하게 하는 option 이다.


필요 없어진 file 지우기

SwiftData 를 들이고 나니 project 에 남는 file 이 생긴다.

  • TripEditModel: SwiftUI view 가 SwiftData model 에 바로 binding 해서 수정을 실시간으로 전하므로 필요 없다.
  • DataSource: 하던 일을 ModelContext, query, relationship 이 알아서 한다.

발표자는 여기서 잠깐 짚는다. project 에서 code 수백 줄이 사라졌고, state 관리, 저장, filtering, 정렬, relationship 탐색, 검색의 상당 부분이 그냥 동작하게 됐다.


model container 연결

model layer 의 마지막은 WindowGroup 이다. modelContainer scene modifier 가 SwiftUI 에게 새 schema 를 @Query 와 함께 쓰라고 알린다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@main
struct WishlistApp: App {
    let container: ModelContainer = {
        do {
            let modelContainer = try ModelContainer(for: Trip.self, Activity.self, TripImage.self, Goal.self, TripGoal.self, ActivityGoal.self)
            try SampleData.seedIfNeeded(in: modelContainer.mainContext)
            return modelContainer
        } catch {
            fatalError("Could not create model container: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .preferredColorScheme(.dark)
        }
        .modelContainer(container)
    }
}

SampleData.seedIfNeeded 는 snippet 에 정의가 없어서 빈 함수로 두고 build 했다. package 는 library 로 build 했기 때문에 @main 은 빼고 확인했다.

modelContainer modifier

[modelContainer(:)](https://developer.apple.com/documentation/swiftui/scene/modelcontainer%28:%29){:target=”_blank”} 는 scene 안의 view 들이 쓸 ModelContainer 를 정한다. 이 container 의 main context 가 environment 에 들어가고 @Query 가 그것을 쓴다.


view layer 고치기

schema 와 model container 가 자리를 잡으면 자동 저장은 기본으로 켜진다. 남은 일은 셋이다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

  • model 을 보여 주는 subview 마다 효율적이고 범위가 좁은 query 를 쓴다.
  • disk 용량 부족이나 지원되지 않는 predicate 처럼 runtime 에 날 수 있는 error 를 잡아 드러낸다.
  • 빠진 property observer 를 되살려서 UI event 가 기대한 data 와 side effect 를 전하게 한다.

filtering 의 위치와 비용

SwiftData 앱에 filtering 을 넣을 때 기억할 점이 둘 있다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

  • query 안에서 FetchDescriptor 가 어느 model 을 읽어 보여 줄지 정한다.
  • model 은 앱의 address space 밖에 있는 저장소에 저장된다. local file system 의 database 일 수도 있고 remote server 일 수도 있다.

이런 저장소는 persistence 의 바탕이지만 memory 에서 읽는 것보다 몇 자릿수 느릴 수 있다. 그래서 어떤 data 가 언제 어디에 있어야 하는지를 따져야 한다.

세션은 세 가지 방식을 RAM 과 I/O 막대로 견준다.

예전에는 trip, activity, goal 이 allGoals 같은 global 변수에 있었다. 앱의 binary 와 함께 load 된다. 접근은 빠르지만 원소를 많이 hardcode 하면 앱이 사는 내내 memory 를 많이 쓴다. 새 goal 을 더해도 앱을 닫으면 사라진다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

SwiftData 로 저장한 뒤 다시 읽는 한 가지 방법은 goal 을 모두 fetch 한 다음 필요 없는 것을 버리는 것이다. 계속 쓰는 memory 는 줄지만 I/O 가 늘어난다. 세션의 비유로는 사서에게 도서관의 모든 책을 가져오게 한 뒤 좋아하는 작가의 책을 직접 고르는 것과 같다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

predicate 로 fetch 하면 처음부터 사서에게 원하는 것을 말하는 셈이다. 요청한 goal 만 돌아온다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

view 에서는 @Query 에 predicate 를 준다. model context 의 fetch 를 부르는 것과 같은 일을 하고, query 결과가 바뀌면 SwiftUI view 가 저절로 갱신된다는 점이 더 좋다.

출처: WWDC26 - Code-along: Add persistence with SwiftData


달성한 goal 과 남은 goal

GoalsView 에서 SwiftData 를 import 하고 environment 의 dataSource 를 query 둘로 바꾼다. 하나는 달성한 goal 을 달성한 때의 역순으로, 다른 하나는 나머지 goal 을 가져온다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
@Query(filter: #Predicate<Goal> { $0.isAchieved }, sort: \Goal.dateAchieved, order: .reverse)
private var achievedGoals: [Goal]

@Query(filter: #Predicate<Goal> { !$0.isAchieved }, sort: \Goal.sortOrder)
private var upcomingGoals: [Goal]

최근 trip 다섯 개

RecentTripsPageView 도 같다. trip 을 만든 때의 역순으로 요청하고 fetch limit 을 5로 둔다. 가장 최근 trip 다섯 개가 ForEach 로 들어간다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct RecentTripsPageView: View {
    // Fetch most recent trips in reverse chronological order
    @Query(FetchDescriptor<Trip>(sortBy: [SortDescriptor(\Trip.creationDate, order: .reverse)], fetchLimit: 5))
    private var trips: [Trip]

    var body: some View {
        TabView {
            ForEach(trips) { trip in
                Text(trip.name)
            }
        }
    }
}

extension FetchDescriptor {
    init(sortBy: [SortDescriptor<T>], fetchLimit: Int) {
        self.init(sortBy: sortBy)
        self.fetchLimit = fetchLimit
    }
}

이 snippet 은 그대로는 build 되지 않았다. Xcode 27.0 의 SDK 에서 FetchDescriptor 의 initializer 는 predicate 와 sortBy 만 받고, fetchLimit 은 만든 뒤에 대입하는 property 다. 그래서 아래의 extension 을 내가 더했다. body 는 snippet 에서 zoom transition 과 overlay 가 붙은 긴 code 인데 query 와 상관없는 부분이라 줄였다.

FetchDescriptor 와 fetchLimit

FetchDescriptor 는 fetch 의 조건과 정렬을 담는 type 이고, fetchLimit 은 돌려줄 model 의 최대 수다.


initializer 에서 만드는 query

TripCollectionView 는 모든 trip 을 계절별로 나눠 보여 준다. 계절 하나가 trip collection 하나이고, collection 마다 이 view 의 instance 가 하나씩 있다. view 는 initialize 될 때까지 어느 계절을 보여 줄지 모른다. 그래서 query 를 선언만 해 두고 initializer 에서 만든다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
struct TripCollectionView: View {
    @Query private var trips: [Trip]
    var tripCollection: TripCollection

    init(tripCollection: TripCollection) {
        _trips = Query(filter: #Predicate<Trip> { $0.collection == tripCollection }, sort: \Trip.name)
        self.tripCollection = tripCollection
    }

    var body: some View {
        ForEach(trips) { trip in Text(trip.name) }
    }
}

predicate 안에서 tripCollection parameter 를 initializer 로부터 바로 capture 한다. 이 값이 database 로 가는 조건이 된다. snippet 은 initializer 만 보여 주고 cardSize, namespace parameter 도 받는다. query 와 무관해서 빼고 view 의 나머지를 채웠다.


검색어로 만드는 query

세 번째 tab 의 SearchResultsListView 는 검색 field 와 text 를 가진 super view 로부터 검색어를 initializer 로 받는다. 여기서도 dataSource 를 query 선언으로 바꾸고, initializer 의 parameter 로 predicate 를 만든다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
struct SearchResultsListView: View {
    @Query(sort: \Trip.name) private var trips: [Trip]
    @Query(sort: \Activity.name) private var activities: [Activity]

    var searchText: String

    init(searchText: String) {
        self.searchText = searchText

        if searchText.isEmpty {
            _trips = Query(FetchDescriptor(sortBy: [SortDescriptor(\Trip.creationDate, order: .reverse)], fetchLimit: 3))
            _activities = Query(filter: #Predicate<Activity> { _ in false })
        } else {
            // All trips whose name matches searchText, sorted lexicographically
            let tripSearchPredicate = #Predicate<Trip> { $0.name.localizedStandardContains(searchText) }
            _trips = Query(filter: tripSearchPredicate, sort: \Trip.name)
            // All matching activities that belong to a trip
            let activitySearchPredicate = #Predicate<Activity> { $0.trip != nil && $0.name.localizedStandardContains(searchText) }
            _activities = Query(filter: activitySearchPredicate, sort: \Activity.name)
        }
    }

    var body: some View {
        List {
            if !trips.isEmpty {
                Section(searchText.isEmpty ? "Recent Trips" : "Trips") {
                    ForEach(trips) { Text($0.name) }
                }
            }
            if !activities.isEmpty {
                Section("Activities") {
                    ForEach(activities) { Text($0.name) }
                }
            }
        }
        .overlay {
            if trips.isEmpty && activities.isEmpty {
                ContentUnavailableView(
                    "No results for “\(searchText)”",
                    systemImage: "magnifyingglass",
                    description: Text("Check spelling or try a new search.")
                )
            }
        }
        .listStyle(.plain)
    }
}
  • 검색어가 비어 있으면 가장 최근 trip 셋으로 대신한다. activity 는 늘 false 인 predicate 로 아무것도 가져오지 않는다.
  • 검색어가 있으면 이름이 검색어와 맞는 trip 을 이름순으로 가져온다.
  • activity 도 같은 식이다. trip 에 속해 있으면서 이름이 맞는 것만 가져온다.

list 에는 검색 결과가 없을 때 ContentUnavailableView 를 띄우는 overlay 가 있다. 원래 dataSource 로 하던 조건을 trips.isEmpty 와 activities.isEmpty 로 바꾼다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

snippet 의 TripSearchSectionView, ActivitySearchSectionView 는 정의가 없어서 Section 과 ForEach 로 바꿨고, namespace parameter 는 뺐다. fetchLimit 을 받는 initializer 는 앞에서 더한 extension 을 쓴다.

여기까지 하면 앱이 다시 실행된다. 발표자는 trip 을 하나 더하고 앱을 다시 실행해서 “Northern Lights” 가 남아 있는 것을 보여 준다.


error 를 잡아 알리기

남은 손질이 몇 가지 있다. ActivityItemView 의 updateGoalAchievements method 는 activity 를 완료할 때 진행 값을 고치고, error 를 던질 수 있다. 발표자는 세 가지를 한다.

  • error 를 state 변수에 담는다.
  • telemetry system 으로 넘겨서 나중에 앱을 고치는 데 쓴다.
  • 알맞은 경우에는 alert 를 띄워서 어떻게 회복하는지 알린다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var body: some View {
    HStack(alignment: .firstTextBaseline, spacing: 17) {
        Text(activity.name)
    }
    .onDisappear {
        do {
            try updateGoalAchievements()
        } catch {
            updateError = error
            reportError(error)
        }
    }
    .alert(error: $updateError) {
        // Customize the presentation of the error
    }
}

updateError 는 @State private var updateError: (any Error)? 로 선언했고 updateGoalAchievements, reportError 는 빈 함수로 두었다. HStack 안의 editing 전환 code 는 Text 하나로 줄였다. alert(error:actions:) 는 SDK 의 SwiftUI 에 선언이 있는 것을 확인했다.


dateEdited 되살리기

UI 에서 state 가 낡는 곳도 있다. 앞에서 dateEdited 를 고치던 didSet 을 지웠기 때문이다.

bug 는 이렇다. activity 를 Date Edited 순으로 정렬해 두고 하나를 완료로 표시하면, 방금 property 가 바뀌었으니 맨 위로 올라가야 한다. 그런데 그대로 있다. persistence 쪽에서는 아무 error 도 나지 않는다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

세션은 OS 27 에서 Observation framework 에 더해진 continuous observation 으로 이것을 되살린다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

ActivityItemView 의 initializer 에서 withContinuousObservation 으로 observer 를 건다. 이 view 가 activity 를 수정하는 곳이라서 observation 을 두기에 알맞다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
init(activity: Activity, isLast: Bool, isEditing: Bool) {
    activity.token = withContinuousObservation(options: .didSet) { event in
        _ = activity.name
        _ = activity.isComplete

        if event.matches(\Activity.name) {
            activity.dateEdited = .now
        }

        if event.matches(\Activity.isComplete) {
            activity.dateEdited = .now
            activity.trip?.isComplete = activity.trip?.activities.isEmpty == false
            && activity.trip?.activities.allSatisfy { $0.isComplete } == true
        }
    }
    self.activity = activity
    self.isLast = isLast
    self.isEditing = isEditing
}

누군가 activity 의 isComplete 나 name 을 바꾸면 Observation 이 이 code 를 실행해서 dateEdited 를 현재 시각으로 고친다. 그러면 query 가 activity 목록을 저절로 갱신한다.

trip 에 대한 side effect 를 두기에도 좋은 자리다. activity 의 상태가 바뀌거나 activity 가 더해지고 빠질 때마다 trip 전체의 isComplete 를 고친다.

closure 는 먼저 name 과 isComplete 를 읽는다. 읽은 property 가 추적 대상이 된다. 그다음 event.matches 로 어느 property 가 바뀌어서 불렸는지 가린다. 이 initializer 는 고치지 않고 build 됐다.

withContinuousObservation 과 Event

withContinuousObservation(options:apply:) 은 closure 가 읽은 observable property 를 계속 추적하고 바뀔 때마다 closure 를 다시 부른다. closure 가 받는 Event 의 matches 는 그 event 가 주어진 key path 의 변화인지 알려 준다. 돌려받은 token 을 들고 있는 동안 추적이 이어지므로 여기서는 activity.token 에 넣어 둔다.


세션의 마무리

세션은 세 가지를 남긴다.

출처: WWDC26 - Code-along: Add persistence with SwiftData

  • 앱의 state 를 어떻게 표현할지 먼저 생각하고, schema 를 이루는 model type 을 선언한다.
  • predicate 를 쓴 좁은 query 로 memory 사용과 disk 저장 사이의 균형을 잡는다.
  • SwiftUI view 가 SwiftData 와 잘 맞물리도록 계속 다듬는다.

정리

원래 codeSwiftData 로 바꾼 뒤
@Observable class@Model class
didSet property observerwithContinuousObservation
닫힌 enum 과 kindclass 와 model inheritance
dictionary 로 흉내 낸 관계배열 property 와 @Relationship
file URLthumbnail Data 와 외부 저장 model
environment 의 DataSourcemodelContainer 와 @Query
memory 에서 filter#Predicate 와 fetchLimit

실제 프로젝트에 가져갈 점은 다음과 같다.

  • macro 를 바꾼 뒤 나오는 build error 가 할 일 목록이다. let property, Codable 이 아닌 type, didSet 순으로 걸린다.
  • 모두 fetch 한 뒤 memory 에서 거르지 않는다. 조건은 predicate 로, 개수는 fetchLimit 으로 database 에 넘긴다.
  • view 가 받는 값에 따라 조건이 달라지면 @Query 를 선언만 하고 initializer 에서 _name = Query(...) 로 만든다.
  • 정렬이나 filtering 에 쓸 값은 stored property 로 둔다. isAchieved 가 그런 예다.
  • 큰 binary 는 화면에 자주 쓰는 작은 version 과 원본으로 나눠 저장한다.
  • 저장이 자동이어도 error 는 난다. 잡아서 기록하고, 사용자가 손쓸 수 있는 경우에만 alert 로 알린다.

관련 글


참고자료

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.