포스트

[WWDC26] What's new in SwiftData

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


세션 정보

  • 세션: What’s new in SwiftData
  • 길이: 12분 53초
  • 공개일: 2026-06-08
  • 발표: Thomas (SwiftData team)
  • 코드: 세션 page 에 snippet 4개

한 줄 요약

@Query 가 결과를 section 으로 나눠 주고, 남의 class 는 .codable attribute 로 저장하고, SwiftUI 밖에서는 ResultsObserver 와 HistoryObserver 로 store 의 변화를 지켜본다.


세션의 구성

세션은 OS 27 release 의 SwiftData 새 기능을 세 묶음으로 다룬다. SwiftData 를 처음 쓴다면 Code-along: Add persistence with SwiftData 를 먼저 보라고 안내한다.

출처: WWDC26 - What’s new in SwiftData

  • Sectioning your fetches: SwiftUI view 에서 Query 로 data 를 section 단위로 가져오기
  • Using custom types: model 에 custom type 을 저장하는 방법의 개선
  • Observing data stores: store 의 model 변화와 history 변화를 지켜보는 새 API

예제는 SwiftData team 이 몇 해째 써 온 SampleTrips 앱이다. 계획한 여행을 기록하는 앱이고, 저장은 SwiftData, 화면은 SwiftUI 다.


section 으로 나눈 fetch

첫 주제는 Query 의 결과를 section 으로 묶는 기능이다.


기존 Query

SwiftUI 에서 SwiftData 를 읽는 방법은 view 에 Query 를 더하는 것이다. 예제의 TripListView 는 모든 trip 을 start date 순으로 가져와 List 에 그린다.

출처: WWDC26 - What’s new in SwiftData

발표자는 여기에 destination 별로 묶어 보는 기능을 더하려 한다. 같은 곳으로 가는 여행이 여럿이면 나란히 보이게 하려는 것이다.


sectionBy parameter

OS 27 에서 Query 는 section 나누기를 지원한다. Trip model 에서 시작해 String 에 이르는 key path 를 새 sectionBy parameter 에 넘긴다. 여기서는 destination 이다.

출처: WWDC26 - What’s new in SwiftData

view 에서는 ForEach 를 두 겹으로 쓴다. 바깥 ForEach 는 section 을 돌고 안쪽 ForEach 는 그 section 의 trip 을 돈다. section 목록은 property wrapper 자체에 있으므로 밑줄이 붙은 이름 _trips 로 접근해서 sections 를 읽는다.

출처: WWDC26 - What’s new in SwiftData

각 section 에는 id 가 있다. sectionBy 에 넘긴 key path 가 가리키는 값이고, 여기서는 그 section 에 든 모든 trip 의 destination 이다. 이것을 Section 의 header 로 쓴다. section 자체가 trip 의 collection 이므로 안쪽 ForEach 는 section 을 그대로 돈다.

출처: WWDC26 - What’s new in SwiftData

build 된 code 는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import SwiftUI
import SwiftData

struct TripListView: View {
    @Query(sort: \Trip.startDate,
           sectionBy: \.destination)
    var trips: SectionedResults<Trip, String>

    var body: some View {
        List {
            ForEach(_trips.sections) { section in
                Section(section.id) {
                    ForEach(section) { trip in
                        TripListItem(trip: trip)
                    }
                }
            }
        }
    }
}

세션과 다른 곳이 세 군데다.

  • 세션은 var trips: [Trip] 으로 두고 wrapped value 가 여전히 Trip 의 배열이라고 설명한다. Xcode 27.0 의 SDK 에서는 이렇게 쓰면 build 되지 않는다. sectionBy 를 받는 initializer 는 wrapped value 의 type 이 SectionedResults<Trip, String> 일 것을 요구한다. 그래서 type 을 바꿨다. 세션을 녹화한 뒤에 API 가 바뀐 것으로 짐작한다.
  • 세션 page 의 snippet 은 안쪽 ForEach 가 trips 를 돈다. 영상의 마지막 화면은 section 을 돈다. 영상 쪽이 설명과 맞으므로 그쪽을 따랐다.
  • snippet 의 List(selection: $selection) 은 selection 선언이 없어서 뺐다. TripListItem 은 이름만 표시하는 view 로 직접 만들었다.

Query 의 sectionBy

Query 의 sectionBy 는 KeyPath<Element, String> 또는 KeyPath<Element, String?> 를 받는다. SDK 의 선언을 보면 section 의 기준은 문자열 property 만 될 수 있다.

SectionedResults 와 ResultsSection

SectionedResults 는 section 의 RandomAccessCollection 이고, 원소인 ResultsSection 은 Identifiable 이면서 model 의 collection 이다. id 와 title 이 같은 값을 돌려준다. SDK 에는 sectionTitles, subscript(sectionTitle:) 같은 member 도 있는데 세션에서는 다루지 않는다.


custom type 의 저장

두 번째 주제는 SwiftData 가 schema 를 만들어 주지 못하는 type 을 model 에 넣는 방법이다.


MapKit 의 identifier 저장하기

SampleTrips 의 중심은 Trip model 이다. name, destination, start date, end date 를 담고, destination 은 지금 String 이다.

출처: WWDC26 - What’s new in SwiftData

발표자는 MapKit 에서 장소를 찾는 기능을 더하려 한다. MapKit 의 search API 로 destination 을 찾는 picker 는 이미 만들어 두었다.

출처: WWDC26 - What’s new in SwiftData

MapKit 은 장소마다 이름, 좌표, 그리고 MKMapItem.Identifier 를 준다. 이 identifier 는 MapKit 안에서 장소를 고유하게 가리키고, 나중에 장소의 metadata 를 더 찾거나 Maps 앱에서 여는 데 쓸 수 있다. 발표자는 좌표와 identifier 를 Trip 에 저장하려 한다.


class property 의 fatal error

property 를 더하고 앱을 실행하면 SwiftData 가 fatal error 를 낸다. persist 되는 struct 나 enum 안의 class property 는 지원하지 않는다는 내용이고, 원인으로 MKMapItem.Identifier 를 가리킨다.

출처: WWDC26 - What’s new in SwiftData

SwiftData 는 load 될 때 model 로부터 schema 를 자동으로 만든다. schema 는 model class 와 data store 가 저장할 수 있는 entity, property 사이의 대응을 정한다. 대부분의 type 은 자동으로 처리된다. 하지만 @Model 이 붙지 않은 class 는 SwiftData 가 들여다볼 수 없어서 schema 를 만들지 못한다.

MKMapItem.Identifier 는 MapKit 의 type 이라 구현에 손을 댈 수 없다. @Model 을 붙일 수도 없다. 다만 Codable 을 따른다. Codable type 은 자신을 data 로 serialize 하고 그 data 에서 다시 만들어지는 방법을 스스로 안다.


codable attribute 란?

.codable 은 model 의 attribute 에 붙이는 option 이다. 이 option 을 붙이면 SwiftData 는 그 type 의 schema 를 추론하지 않고, serialization 을 type 에 맡긴 뒤 encode 된 결과를 저장한다.

출처: WWDC26 - What’s new in 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
import Foundation
import MapKit
import SwiftData

@Model class Trip {

    struct Location: Codable {
        var latitude: Double
        var longitude: Double
    }

    var name: String
    var destination: String

    var startDate: Date
    var endDate: Date

    var location: Location?
    @Attribute(.codable) var mapItemIdentifier: MKMapItem.Identifier?

    init(name: String, destination: String, startDate: Date, endDate: Date) {
        self.name = name
        self.destination = destination
        self.startDate = startDate
        self.endDate = endDate
    }
}

snippet 에는 import SwiftData 만 있고 init 이 없다. import Foundation, import MapKit 과 init 을 더해서 build 했다. 세션에서는 이 attribute 를 붙인 뒤 앱이 error 없이 실행된다.

좌표를 담는 Location 은 직접 정의한 Codable struct 이고 .codable 없이 저장된다. SwiftData 가 struct 는 들여다볼 수 있기 때문이다.

codable option

codable 은 Schema.Attribute.Option 의 값이고, Attribute macro 에 넘긴다. SDK 에는 OS 27 부터 쓸 수 있다고 표시되어 있다.


codable attribute 의 제약

transformable attribute 와 마찬가지로 알아 둘 점이 있다.

출처: WWDC26 - What’s new in SwiftData

  • 내용이 SwiftData 에게 불투명하다. Predicate 로 걸러 내거나 SortDescriptor 로 정렬하는 데 쓸 수 없다.
  • type 의 모양이 바뀌어도, 예를 들어 property 를 더하거나 빼도 migration 이 일어나지 않는다. 그 type 의 Codable 구현이 앞뒤 version 모두와 호환되게 encode, decode 할 수 있어야 한다.

세션은 codable attribute 를 SwiftData 가 직접 지원하지 않는 type 을 저장하기 위한 escape hatch 로 보라고 말한다. 직접 정의하는 type 에는 쓰지 않는 편이 좋다. SwiftData model 이나 지원되는 value type 으로 만들어야 정렬, filtering, indexing 을 온전히 쓸 수 있다. 소유하지 않은 type 일 때 다른 attribute 옆에 함께 저장하는 용도다.


store 의 변화 관찰

세 번째 주제는 data 가 바뀌었을 때 알림을 받는 방법이다.


Query 가 하는 일

@Query 는 view 가 나타날 때 store 에서 model 을 가져와 view body 에서 쓸 수 있게 한다. 그 뒤로는 결과에 영향을 줄 변화가 있는지 store 를 계속 지켜본다. trip 하나가 지워지면 Query 가 알아채고 view 가 새 결과로 다시 그려진다.

출처: WWDC26 - What’s new in SwiftData

SwiftUI view 에서는 Query 가 첫 번째 선택이어야 한다. 그런데 SwiftUI 가 아닌 부분도 있다. store 의 값으로부터 무언가를 계산해 두고 data 가 바뀌면 다시 계산해야 하는 state object 가 그렇고, SceneKit 으로 만든 game 처럼 SwiftUI 를 아예 쓰지 않는 앱도 그렇다.


ResultsObserver 란?

ResultsObserver 는 Query 가 하는 일을 SwiftUI view 밖에서 하는 class 다. store 에서 data 를 가져오고 그 뒤로 변화를 지켜본다. 변화는 Swift Observation 으로 알린다. Query 와 같은 기본 요소인 filtering, 정렬, section 나누기를 지원한다.

출처: WWDC26 - What’s new in SwiftData

앞의 흐름 그림에서 Query 자리에 ResultsObserver 가, view 자리에 임의의 code 가 들어간 모양이다.

출처: WWDC26 - What’s new in SwiftData


지도 영역을 다시 계산하는 예

발표자는 여행지를 모두 보여 주는 지도를 더한다. SwiftUI 의 MapKit 통합을 쓰되 지도의 어느 영역을 보여 줄지는 직접 정하고 싶어서 MapCameraController 를 만들었다. 이 controller 가 알맞은 MapCameraBounds 를 계산하고, 다시 계산할 시점을 ResultsObserver 로 안다.

출처: WWDC26 - What’s new in SwiftData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import SwiftUI
import MapKit
import SwiftData
import Observation

@Observable @MainActor final class MapCameraController {
    private let resultsObserver: ResultsObserver<Trip, Never>
    var bounds: MapCameraBounds?
    @ObservationIgnored private var token: ObservationTracking.Token?

    init(modelContext: ModelContext) throws {
        resultsObserver = try ResultsObserver<Trip, Never>(modelContext: modelContext)

        token = withContinuousObservation(options: [.didSet]) { [weak self] event in
            guard let self else { return }
            self.bounds = self.calculateBounds(trips: Array(self.resultsObserver.results))
        }
    }

    private func calculateBounds(trips: [Trip]) -> MapCameraBounds? { nil }
}

지도에는 늘 모든 trip 을 보여 줄 것이므로 predicate 도 section key path 도 넘기지 않는다. 그다음 withContinuousObservation 을 didSet option 으로 불러서 trip 이 바뀔 때마다 callback 을 받고, 그 안에서 bounds 를 다시 계산한다.

withContinuousObservation 은 ObservationTracking token 을 돌려준다. 이 token 이 observation 의 수명을 정한다. class 에 저장해 두면 controller 가 살아 있는 동안 계속 알림을 받는다.

출처: WWDC26 - What’s new in SwiftData

세션과 다른 곳은 다음과 같다. 모두 Xcode 27.0 에서 build 하려고 고친 것이다.

  • token 에 @ObservationIgnored 를 붙였다. ObservationTracking.Token 은 noncopyable type 이라서 @Observable 이 추적하는 property 가 될 수 없다는 error 가 난다.
  • resultsObserver.results 의 type 은 [Trip] 이 아니라 FetchResultsCollection<Trip> 이다. Array 로 감싸서 넘겼다.
  • closure 안에서 self 를 guard let 으로 풀었다. 세션처럼 self?. 로 쓰고 resultsObserver 를 그냥 참조하면 self 를 명시하라는 error 가 난다.
  • 영상의 화면은 ResultsObserver<Trip> 으로 쓰지만 SDK 의 type 은 generic parameter 가 둘이다. snippet 의 ResultsObserver<Trip, Never> 가 맞다. section 을 쓰지 않을 때 두 번째 자리가 Never 다.
  • snippet 의 closure 머리 {[weak self], event in 은 쉼표가 잘못 들어간 것이라 뺐고, calculateBounds 의 본문은 생략되어 있어서 nil 을 돌려주게 했다.

데모에서는 앱을 실행하면 controller 가 모든 trip 이 들어오는 bounds 를 고른다. Toronto 여행을 지우면 ResultsObserver 가 변화를 알아채고 controller 가 bounds 를 다시 계산해서 지도가 남은 여행지 쪽으로 좁혀진다.

출처: WWDC26 - What’s new in SwiftData

ResultsObserver

ResultsObserver 는 ModelContext 나 ModelContainer 로 만든다. SDK 의 선언에는 filterBy, sortBy, sectionBy 를 받는 initializer 와 results, sections property 가 있다. results 는 FetchResultsCollection 이다.

withContinuousObservation

withContinuousObservation(options:apply:) 은 Observation framework 의 함수다. closure 안에서 읽은 observable property 를 추적하고, 바뀔 때마다 closure 를 다시 부른다. 돌려주는 Token 이 사라지면 추적도 끝난다.

MapCameraBounds

MapCameraBounds 는 SwiftUI 의 Map 에서 camera 가 움직일 수 있는 범위를 정하는 type 이다.


history 의 관찰

OS 27 은 fetch 결과뿐 아니라 history 를 지켜보는 것도 지원한다.


persistent history

store 의 data 가 바뀌면 SwiftData 는 무엇이 바뀌었는지 기록을 남긴다. 이 history 로 외부 server 와 sync 하거나, app extension 처럼 앱 밖에서 일어난 변화에 반응하는 기능을 만들 수 있다.

출처: WWDC26 - What’s new in SwiftData

store 가 저장될 때마다 history transaction 하나가 기록된다. transaction 에는 무엇이 바뀌었는지, 그 변화가 어디서 왔는지, 그리고 history 안에서 그 transaction 을 고유하게 가리키는 token 이 들어 있다. 이 token 을 [fetchHistory(:)](https://developer.apple.com/documentation/swiftdata/modelcontext/fetchhistory%28:%29){:target=”_blank”} 에 넘기면 그보다 새로운 transaction 을 가져올 수 있다. 자세한 내용은 Track model changes with SwiftData history (WWDC24) 에 있다.


HistoryObserver 란?

HistoryObserver 는 persistent history 를 지켜보다가 새 transaction 이 더해지면 알려 주는 class 다. ResultsObserver 가 fetch 결과를 지켜보는 것과 짝을 이룬다. 특정 종류의 변화만 알고 싶으면 model type 과 transaction author 로 거를 수 있다. 외부 server 처럼 다른 system 과 store 의 일부를 맞춰 두어야 할 때 쓸모가 있다.

출처: WWDC26 - What’s new in SwiftData

관찰할 수 있는 property 는 eventCounter 하나뿐이다. history 에 새 transaction 이 생기면 이 값이 오른다. code 는 eventCounter 를 지켜보다가 값이 오르면 fetchHistory 로 최신 변화를 가져온다.

출처: WWDC26 - What’s new in SwiftData


server 와 sync 하는 예

앱에서 일어난 변화를 외부 server 로 보내는 예다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import SwiftData
import Observation

@globalActor actor SyncActor { static let shared = SyncActor() }

@SyncActor final class ServerSync {
    private var observer: HistoryObserver?
    private var token: ObservationTracking.Token?
    private let modelContainer: ModelContainer

    init(modelContainer: ModelContainer) { self.modelContainer = modelContainer }

    func start() throws {
        self.observer = try HistoryObserver(authors: ["App"], modelContainer: modelContainer)
        token = withContinuousObservation(options: .didSet) { [weak self] _ in
            _ = self?.observer?.eventCounter
            self?.processChanges()
        }
    }

    private func processChanges() {
        // Fetch and process history transactions
    }
}

먼저 model container 에 대한 HistoryObserver 를 만든다. 앱이 만든 변화에만 관심이 있으므로 authors 에 "App" 을 넘긴다. server 에서 온 변화를 server 로 되돌려 보내지 않기 위해서다.

다음은 withContinuousObservation 이다. MapCameraController 와 마찬가지로 token 을 class 에 저장해서 class 가 살아 있는 동안 추적이 이어지게 한다. closure 안에서는 eventCounter 를 읽어야 한다. 값을 쓰지 않더라도 읽어야 Swift Observation 이 무엇을 추적할지 안다. 마지막으로 processChanges 를 부르고, 그 안에서 fetchHistory 로 history 를 가져와 server 에 올린다.

출처: WWDC26 - What’s new in SwiftData

세션과 다른 곳은 다음과 같다.

  • SyncActor 는 snippet 에 정의가 없어서 global actor 로 직접 만들었다.
  • snippet 은 observer 를 let 으로 선언하고 start() 에서 대입한다. 이대로는 build 되지 않아서 optional var 로 바꿨다.
  • modelContainer 가 어디서 오는지 snippet 에 없어서 stored property 와 init 을 더했다.

processChanges 의 본문은 세션에서도 주석뿐이다. history 를 가져와 처리하는 부분은 이 글에서 확인한 것이 없다.

HistoryObserver

HistoryObserver 의 initializer 는 SDK 에서 historyTokens, observedModels, authors, modelContainer 를 받는다. authors 는 Set<String> 이다. eventCounter 는 Int 다.


세션의 마무리

세션은 네 가지를 권하며 끝난다.

출처: WWDC26 - What’s new in SwiftData

  • fetch 를 section 으로 나눈다.
  • 다른 framework 의 type 을 저장할 때 codable attribute 를 쓴다.
  • SwiftUI view 밖에서 query 결과의 변화에 반응할 때 ResultsObserver 를 쓴다.
  • persistent history 의 변화에 반응할 때 HistoryObserver 를 쓴다.

정리

하려는 일쓰는 것알아 둘 점
list 를 묶어서 보여 주기@Query(sectionBy:) 와 sections기준은 String key path
손댈 수 없는 class 를 model 에 저장@Attribute(.codable)predicate, 정렬 불가. migration 없음
SwiftUI 밖에서 fetch 결과 따라가기ResultsObserver + withContinuousObservationtoken 을 저장해 두어야 추적이 이어짐
새 history transaction 에 반응HistoryObserver 의 eventCounterclosure 안에서 counter 를 읽어야 추적됨

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

  • SwiftUI view 에서는 여전히 @Query 가 먼저다. observer 는 view 가 아닌 곳을 위한 것이다.
  • .codable 은 소유하지 않은 type 에만 쓴다. 직접 만든 type 은 model 이나 지원되는 value type 으로 둔다.
  • .codable 로 저장한 type 은 모양이 바뀌어도 SwiftData 가 migration 해 주지 않으므로, 그 type 의 Codable 구현이 version 간 호환을 책임지는지 먼저 확인한다.
  • sync 용 HistoryObserver 에는 author 를 걸어서 server 에서 받은 변화를 되돌려 보내지 않게 한다.
  • 세션의 code 를 그대로 옮기면 Xcode 27.0 에서 build 되지 않는 곳이 있다. @Query(sectionBy:) 의 property type, @Observable class 안의 token, results 의 type 을 확인한다.

관련 글


참고자료

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