포스트

[WWDC26] What's new in SwiftUI

이 글은 WWDC 세션의 transcript 와 코드를 Claude Code 로 정리한 글이고, 실제로 쓴 날은 2026-11-24 다. 코드는 Xcode 27.0 (Swift 6.4) 에서 iOS 27 SDK 대상으로 빌드했다.


세션 정보

  • 세션: What’s new in SwiftUI (WWDC26, 세션 269)
  • 길이: 28분 15초
  • 발표: UI Frameworks 팀의 Steven, Julia
  • 다루는 버전: Xcode 27, iOS 27 과 같은 해의 OS 들 (세션에서는 2027 releases 라고 부른다)

한 줄 요약

2027 releases 의 SwiftUI 는 코드를 바꾸지 않아도 따라오는 변화 (새 Liquid Glass, AsyncImage cache, lazy 한 @State, 빨라진 type check) 와 새로 쓸 수 있는 API (toolbar 우선순위, 새 Document API, reorderable container, 어디서나 되는 swipe action) 두 갈래로 나뉜다.

세션은 sticker 를 사진에 붙이는 예제 앱 하나를 놓고 네 부분으로 진행된다. look and feel, document 기반 앱, presentation 과 interaction, data flow 와 performance 순서다.


새로워진 look and feel

2027 releases 로 빌드하면 Liquid Glass 가 새 모습으로 바뀐다. 코드는 한 줄도 고칠 필요가 없다. 이 장은 그렇게 자동으로 따라오는 것을 먼저 보여 주고, 세밀하게 손볼 수 있는 API 를 이어서 소개한다.

출처: WWDC26 - What’s new in SwiftUI

자동으로 바뀌는 것은 세 가지다.

  • Liquid Glass 의 모양이 다듬어졌고, 사용자가 tint 를 조절하는 새 Liquid Glass slider 에 자동으로 반응한다
  • macOS 에서도 iOS 처럼 custom Liquid Glass 요소를 interactive 로 표시할 수 있다. 클릭에 더 부드럽게 반응하고, 마우스 pointer 에 맞게 조정되어 있다
  • iPad 앱이 Mac 처럼 비활성 window 에서 다른 모습을 띤다. 아이콘과 텍스트가 흐려져서 어느 window 가 active 인지 알려 준다

출처: WWDC26 - What’s new in SwiftUI


비활성 window 대응

시스템이 그리는 tab label 은 알아서 흐려지지만 직접 만든 view 는 그렇지 않다. 예제 앱의 sidebar 아래에 있는 계정 버튼이 그런 경우다.

1
2
3
4
5
6
7
8
struct SidebarFooterView: View {
    @Environment(\.appearsActive) private var appearsActive

    var body: some View {
        MyAccountView()
            .opacity(appearsActive ? 1 : 0.5)
    }
}

appearsActive 로 window 활성 상태 읽기

appearsActive 는 view 가 속한 window 가 active 로 보이는지 알려 주는 environment 값이다. 값이 false 일 때 opacity 를 낮추면 custom view 도 주변 tab label 과 같이 흐려진다. 이 값 자체는 새 API 가 아니고 iOS 18 부터 있었다. 달라진 것은 iPad 에서도 비활성 window 가 흐려지게 되면서 쓸 자리가 늘었다는 점이다.


iPad 와 Mac 의 menu bar 는 이제 기본으로 아이콘을 최소한만 보여 준다. 아이콘은 핵심 동작에만 남긴다는 방침이다. 특정 항목의 아이콘을 꼭 보여 주고 싶으면 그 항목에만 label style 을 지정한다.

1
2
3
4
5
6
7
CommandMenu("Stickers") {
    Button { openStore() } label: {
        Label("Store", systemImage: "bag.fill")
            .labelStyle(.titleAndIcon)
    }
    // Other menu items
}

세션 Code 탭의 원문에는 닫는 중괄호가 하나 더 들어 있어서 그대로는 빌드되지 않는다. 위 코드는 중괄호를 맞춘 것이고, Commands 를 따르는 struct 의 body 안에 넣어서 빌드했다.

titleAndIcon 으로 menu 항목 아이콘 보이기

titleAndIcon 은 제목과 아이콘을 둘 다 보여 주는 label style 이다. 기본이 아이콘 생략으로 바뀌었기 때문에, 이 style 을 붙인 항목만 아이콘이 남아서 눈에 띈다.


iPhone 앱 resize

iOS 27 부터는 iPhone 앱도 크기가 바뀐다. iPhone Mirroring 으로 띄우거나 iPad 에서 iPhone 앱으로 실행할 때가 그렇다. Xcode 27 의 Live Preview 에는 resize handle 이 생겨서, 앱이 크기 변화에 어떻게 반응하는지 preview 에서 바로 끌어 보며 확인할 수 있다.

SwiftUI 로만 만든 앱은 대부분 자동으로 대응된다. UIKit 과 SwiftUI 를 같이 쓰는 앱은 세 가지를 더 챙겨야 한다고 세션은 짚는다.

  • screen geometry 를 올바르게 구하는 방법
  • view 크기를 정할 때 idiom 대신 size class 를 쓰는 것
  • interface orientation 변화에 대응하는 것

자세한 내용은 Modernize your UIKit app 세션으로 넘긴다.


prominent tab

예제 앱에는 sticker pack 을 받는 store 화면이 있고, tab 중 하나가 장바구니다. 장바구니는 store 내용을 담은 다른 tab 과 성격이 달라서 화면 아래 trailing 쪽에 따로 떨어져 나온다.

1
2
3
4
5
6
7
8
9
TabView {
    Tab { EventsTab() }
    Tab { HolidaysTab() }
    Tab { FunTab() }

    Tab(role: .prominent) {
        CartTab()
    }
}

출처: WWDC26 - What’s new in SwiftUI

prominent role 로 tab 을 따로 배치하기

prominent 는 2027 releases 에 추가된 TabRole 이다. 이 role 을 준 tab 은 나머지 tab 묶음과 분리되어 bottom trailing 에 놓인다. 검색 tab 을 떼어 놓던 .search role 과 비슷한 자리를, 검색이 아닌 tab 에도 쓸 수 있게 된 셈이다.


toolbar 항목 우선순위

window 를 줄이면 시스템이 toolbar 항목을 자동으로 조정하고, 들어가지 않는 항목은 overflow menu 로 숨긴다. iPhone 처럼 가로 공간이 좁으면 Undo, Redo, Share 같은 중요한 버튼까지 overflow menu 로 들어가 버린다. 새 toolbar API 는 공간이 모자랄 때 어떤 버튼을 남길지 직접 정하게 해 준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
StickerPageView()
    .toolbar {
        ToolbarItemGroup {
            UndoButton()
            RedoButton()
        }
        .visibilityPriority(.high)
        ToolbarOverflowMenu {
            ChoosePhotoButton()
            ExportAsImageButton()
            ClearAllStickersButton()
        }
        ToolbarItem(placement: .topBarPinnedTrailing) {
            ShareButton()
        }
    }

출처: WWDC26 - What’s new in SwiftUI

세 API 가 각각 다른 요구를 맡는다.

visibilityPriority 로 남길 항목 정하기

[visibilityPriority(:)](https://developer.apple.com/documentation/swiftui/toolbarcontent/visibilitypriority%28:%29){:target=”_blank”} 는 toolbar content 에 붙이는 modifier 다. .high 를 주면 공간이 모자랄 때 다른 항목보다 나중에 숨는다. 예제에서는 편집에 꼭 필요한 Undo 와 Redo 묶음에 붙였다. 값은 .automatic, .low, .high 가 있다.

ToolbarOverflowMenu 로 항상 menu 에 두기

ToolbarOverflowMenu 는 반대 방향의 요구를 맡는다. 자주 쓰지 않는 동작은 공간이 남아도 처음부터 overflow menu 에 넣어 둔다. 예제에서는 사진 바꾸기, 이미지로 내보내기, sticker 전부 지우기가 여기에 들어간다. SDK 를 보면 macOS, tvOS, watchOS 에서는 쓸 수 없다.

topBarPinnedTrailing 으로 항상 보이게 고정하기

topBarPinnedTrailing 은 항목을 trailing 끝에 고정하는 placement 다. 어떤 크기에서도 숨지 않는다. 예제에서는 Share 버튼에 썼다. 이것도 macOS 에서는 쓸 수 없다.


스크롤할 때 숨는 navigation bar

sticker 목록을 스크롤할 때는 목록에 공간을 최대한 주고 싶다. modifier 하나로 아래로 스크롤할 때 navigation bar 가 비켜나게 할 수 있다.

1
2
3
4
ScrollView {
    StickerListView()
}
.toolbarMinimizationBehavior(.onScrollDown, for: .navigationBar)

세션의 발표와 Code 탭은 이 modifier 를 toolbarMinimizeBehavior 라고 부른다. Xcode 27.0 의 SDK 에는 그 이름이 없고 toolbarMinimizationBehavior 로 들어 있다. 세션 표기대로 쓰면 빌드되지 않아서 위 코드는 실제 이름으로 고쳤다.

toolbarMinimizationBehavior 로 bar 최소화 조건 정하기

[toolbarMinimizationBehavior(:for:)](https://developer.apple.com/documentation/swiftui/view/toolbarminimizationbehavior%28:for:%29){:target=”_blank”} 는 어떤 bar 를 언제 최소화할지 정한다. 첫 인자는 .automatic, .onScrollDown, .onScrollUp, .never 중 하나고, for: 에는 대상 bar 를 넘긴다.


document 기반 앱

SwiftUI 는 예전부터 FileDocument 와 ReferenceFileDocument 로 document 기반 앱을 지원했다. 2027 releases 에는 그 위에 새 Document API 가 올라간다. 예제 앱이 sticker page 를 열고 저장하고 이미지로 내보내는 기능은 전부 이 API 로 만든 것이다.

document 기반 앱은 틀만 갖춰도 얻는 것이 많다. Pixelmator Pro, Pages, Xcode 가 그런 앱이다.

  • 새 document 를 만드는 Command+N, 여는 Command+O 같은 keyboard shortcut
  • document 에 변경이 있음을 알려 주는 edited indicator
  • autosave

세션은 새 API 가 주는 개선으로 세 가지를 든다. document creation context, disk 읽기와 쓰기 성능, document URL 직접 접근이다. 이 가운데 앞의 두 가지를 코드로 보여 준다.

SDK 에서는 기존 FileDocument 계열에 “Use the Document protocol and URLDocumentConfiguration.” 이라는 deprecation 메시지가 붙어 있다. 새 API 가 기존 것을 대체하는 방향임을 알 수 있다.


document creation source

기본 document 앱은 빈 document 로 시작한다. 예제 앱은 사진에서 바로 시작하는 버튼을 하나 더 둔다.

출처: WWDC26 - What’s new in SwiftUI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@main
struct Stickers: App {
    var body: some Scene {
        DocumentGroupLaunchScene("Create a Sticker Page") {
            NewDocumentButton("New Sticker Page", source: .blank)
            NewDocumentButton("Sticker Page from Photo…", source: .photo)
        }

        DocumentGroup { document in
            StickerPageDocumentView(document)
        } makeDocument: { configuration, context in
            StickerDocument(configuration: configuration, context: context)
        }
    }
}

extension DocumentCreationSource {
    static let blank = Self(id: "blank")
    static let photo = Self(id: "photo")
}

세션 코드는 두 번째 closure 를 label 없는 trailing closure 로 쓰고 document 타입 이름도 StickerPageDocument 와 StickerDocument 가 섞여 있다. 위 코드는 타입 이름을 StickerDocument 로 맞추고 makeDocument: label 을 붙여서 빌드한 것이다.

DocumentCreationSource 로 생성 경로 선언하기

DocumentCreationSource 는 document 가 어떤 경로로 만들어졌는지 나타내는 값이다. id 문자열로 만들고, 보통 위처럼 static 상수로 선언해 둔다. SDK 에서 init(id:) 는 macOS 에서 쓸 수 없다.

NewDocumentButton 으로 launch scene 에 버튼 추가하기

NewDocumentButton 은 DocumentGroupLaunchScene 에 넣는 새 document 버튼이다. 둘 다 iOS 18 에 나온 API 고, 이번에 source: 를 받는 형태가 추가됐다. 버튼마다 다른 source 를 주면 어느 버튼으로 만들었는지 구분된다.

DocumentGroup 의 makeDocument 에서 context 받기

DocumentGroup 의 새 initializer 는 editor 와 makeDocument 두 closure 를 받는다. makeDocument 는 URLDocumentConfiguration 과 DocumentCreationContext 를 받아서 document 를 만든다. 버튼을 누르면 SwiftUI 가 그 버튼의 source 를 context.creationSource 에 담아 넘긴다.

document 의 initializer 에서 이 값을 확인한다. 세션은 initializer 코드를 보여 주지 않고 말로만 설명하는데, 빌드해 본 형태는 이렇다.

1
2
3
init(configuration: URLDocumentConfiguration, context: DocumentCreationContext) {
    showsPhotoPicker = context.creationSource == .photo
}

source 가 photo 면 photo picker 를 띄운 채로 document 가 열린다. 사진에 sticker 를 붙이기까지 탭 한 번이 줄어든다.

URLDocumentConfiguration 에는 fileURL 이 들어 있다. 세션이 세 번째 개선으로 든 document URL 직접 접근이 이 타입을 가리키는 것으로 보이는데, 세션에서 코드로 다루지는 않았다.


document 선언

앱을 document 구조로 만들려면 DocumentGroup 을 App 의 body 에서 첫 번째 Scene 으로 선언한다.

1
2
3
4
5
6
7
@main
struct Stickers: App {
    var body: some Scene {
        DocumentGroup { /* ... */ }
        WindowGroup { /* ... */ }
    }
}

document 타입은 class 로 만든다. view 에 data 를 주고, disk 에서 읽는 방법과 다시 쓰는 방법을 설명하는 역할이다.

1
2
3
4
@Observable
final class StickerDocument {
    // ...
}

새 Document API 는 Observation framework 와 함께 동작하도록 만들어졌다. @Observable 을 붙이는 것만으로 성능 이득이 하나 생긴다. view 는 자신이 읽는 property 가 바뀔 때만 다시 그려진다. document 앱은 UI 가 복잡하고 자주 갱신되므로 이 차이가 크다.


WritableDocument 란?

WritableDocument 는 document 를 disk 에 쓰는 방법을 설명하는 protocol 이다. 요구 사항은 세 가지다.

  1. 앱이 쓸 수 있는 format 목록
  2. 지금 document 내용을 돌려주는 snapshot 메서드
  3. 실제로 disk 에 쓰는 writer 를 만드는 메서드

핵심은 쓰기를 두 단계로 나눈다는 점이다. main actor 에서는 내용을 snapshot 으로 떠 놓기만 하고, 오래 걸리는 disk 작업은 writer 가 background 에서 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Observable
final class StickerDocument: WritableDocument {

    static let writableContentTypes: [UTType] = [.stickerDocument]

    @MainActor
    func snapshot(contentType: UTType) async throws -> sending PageSnapshot {
        makeSnapshot()
    }

    func writer(configuration: sending WriteConfiguration) -> sending Writer {
        Writer(contentType: configuration.contentType)
    }
}

extension UTType {
    static let stickerDocument = UTType(exportedAs: "stickerdocument")
}

세션의 앞쪽 코드는 format 목록의 이름을 writableDocumentTypes 로 적었다. SDK 의 protocol 요구 사항은 writableContentTypes 고, 세션도 뒤쪽 코드와 슬라이드에서는 이 이름을 쓴다. 위 코드는 writableContentTypes 로 통일했다.

예제 앱의 format 은 사진과 sticker 가 들어 있는 custom package 다. snapshot 은 직접 정의한 struct 로 표현한다.

1
2
3
4
5
6
7
struct PageSnapshot {
    var background: Image
    var metadata: StickerPlacements
    var stickers: [Image]
}

struct StickerPlacements { /* ... */ }

쓰기에 필요한 것이 전부 들어 있다. 배경 이미지, sticker 좌표, sticker 자체다. 어느 한 시점의 document 를 그대로 떠 놓은 값이라고 보면 된다.


DocumentWriter 란?

DocumentWriter 는 snapshot 을 받아 지정한 format 으로 disk 에 쓰는 protocol 이다. WritableDocument 의 짝이고, 요구 사항은 write 메서드 하나다.

1
2
3
4
5
6
7
8
9
10
11
12
struct Writer: DocumentWriter {

    let contentType: UTType

    nonisolated func write(
        snapshot: sending PageSnapshot, to destination: URL,
        previous: sending PageSnapshot?, progress: consuming Subprogress
    ) async throws {
        // report progress…
        // write .stickerDocument
    }
}

세션 코드는 struct Writer<Snapshot>: DocumentWriter 로 generic parameter 를 두고 안에서 typealias Snapshot = PageSnapshot 을 선언한다. 이 형태는 writer(configuration:) 의 반환 타입 Writer 에서 “reference to generic type ‘Writer’ requires arguments” 에러가 나서 빌드되지 않았다. 위 코드는 generic parameter 를 뺀 것이다. Snapshot 은 write 의 parameter 타입에서 추론된다.

세션은 이 메서드가 성능을 챙길 자리를 세 군데 준다고 설명한다.

  • nonisolated async: 비용이 큰 disk 쓰기를 background 에서 하므로 앱이 계속 반응한다. SDK 의 요구 사항에는 @concurrent 가 붙어 있다
  • previous snapshot: 지금 snapshot 과 이전 snapshot 을 비교해서 package 에서 실제로 바뀐 부분만 쓴다
  • progress: 그래도 시간이 걸릴 수 있으므로 진행률을 보고한다

Subprogress 로 쓰기 진행률 보고하기

Subprogress 는 Foundation 의 진행률 보고 타입이다. SwiftUI 가 progress parameter 로 넘겨 주고, writer 는 여기에 진행 상황을 채운다. 세션은 parameter 가 있다는 것까지만 보여 주고 보고하는 코드는 주석으로 남겼다.


ReadableDocument 와 DocumentReader

읽기는 ReadableDocument 를 따르면 된다. 세션은 이 protocol 을 WritableDocument 의 쌍둥이라고 부르고 둘을 나란히 놓고 비교한다.

출처: WWDC26 - What’s new in SwiftUI

 WritableDocumentReadableDocument
content type 목록writableContentTypesreadableContentTypes
snapshotsnapshot(contentType:) 으로 제공apply(snapshot:previous:) 로 반영
짝 protocol 을 만드는 메서드writer(configuration:)reader(configuration:)
짝 protocolDocumentWriter 의 write(snapshot:to:previous:progress:)DocumentReader 의 read(from:progress:)

쓰기와 방향만 반대다. DocumentReader 가 background 에서 disk 를 읽어 snapshot 을 만들고, document 는 main actor 에서 그 snapshot 을 자기 상태에 반영한다.

세션 코드는 conformance 선언의 빈 껍데기만 보여 준다.

1
2
3
extension StickerDocument: ReadableDocument {

}

이대로는 빌드되지 않는다. SDK 의 요구 사항에 맞춰 최소한으로 채운 형태는 이렇다. 내용은 직접 채운 것이고 세션에 나온 코드가 아니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Reader: DocumentReader {
    func read(from source: sending URL, progress: consuming Subprogress) async throws -> sending PageSnapshot {
        // disk 에서 읽어 snapshot 만들기
    }
}

extension StickerDocument: ReadableDocument {
    static let readableContentTypes: [UTType] = [.stickerDocument]

    func reader(configuration: sending ReadConfiguration) -> sending Reader {
        Reader()
    }

    @MainActor
    func apply(snapshot: sending PageSnapshot, previous: sending PageSnapshot?) async throws {
        // snapshot 을 document 상태에 반영하기
    }
}

하나 더 필요한 것이 있었다. DocumentGroup 의 새 initializer 는 document 타입이 Document 를 따를 것을 요구한다. Document 는 ReadableDocument 와 WritableDocument 를 합친 protocol 이다. 두 protocol 을 각각 따르는 것만으로는 부족해서 extension StickerDocument: Document {} 를 추가해야 빌드됐다.


다른 format 으로 내보내기

앱이 없는 사람에게도 보낼 수 있게 page 를 이미지로 저장하는 기능을 더한다. writer 를 확장하면 된다. 먼저 쓸 수 있는 content type 에 PNG 를 추가한다.

1
static let writableContentTypes: [UTType] = [.stickerDocument, .png]

그리고 write 에서 content type 별로 갈라 쓴다.

1
2
3
4
5
6
7
8
9
10
nonisolated func write(
    snapshot: sending PageSnapshot, to destination: URL,
    previous: sending PageSnapshot?, progress: consuming Subprogress
) async throws {
    if contentType.conforms(to: .stickerDocument) {
        // write .stickerDocument
    } else if contentType.conforms(to: .png) {
        // Core Graphics 로 sticker 와 배경 사진을 한 장으로 합쳐서 쓰기
    }
}

세션 코드의 PNG 분기에는 CGContext(/* ... */) 와 context.draw(/* ... */) 가 인자를 생략한 채 들어 있다. 그대로는 빌드되지 않아서 주석으로 바꿨다. 하는 일은 sticker 와 배경 사진을 Core Graphics 로 이미지 한 장에 합쳐서 URL 에 쓰는 것이다.

writer 가 contentType 을 들고 있는 이유가 여기서 드러난다. content type 을 하나 더 추가하고 분기를 하나 더 쓰면, 어떤 framework 로든 어떤 format 이든 쓸 수 있다.


presentation 과 interaction

이 장은 sticker 목록 화면에서 쓰는 세 가지 개선을 다룬다. 순서 바꾸기, swipe action, 그리고 dialog 를 띄우는 방식이다. 공통점은 List 에서만 되던 것이 다른 container 에서도 된다는 것이다.


reorderable container

예제 앱의 inspector 는 sticker 를 이름과 함께 List 로 보여 준다. 끌어서 순서를 바꾸게 하려면 modifier 두 개를 붙인다.

1
2
3
4
5
6
7
8
9
List {
    ForEach(stickers) { sticker in
        StickerListItemView(sticker: sticker)
    }
    .reorderable()
}
.reorderContainer(for: Sticker.self) { difference in
    difference.apply(to: &stickers)
}

drag interaction 과 animation 은 SwiftUI 가 처리한다. 앱이 할 일은 closure 에서 배열의 순서를 실제로 바꾸는 것뿐이다.

reorderable 로 순서 바꿀 항목 표시하기

reorderable() 은 ForEach 같은 DynamicViewContent 에 붙인다. 이 항목들이 순서를 바꿀 수 있는 대상임을 알린다.

reorderContainer 로 변경 받기

reorderContainer(for:isEnabled:move:) 는 container 쪽에 붙인다. 사용자가 항목을 옮기면 closure 가 불리고, 무엇을 어디로 옮겼는지가 ReorderDifference 로 들어온다. sources 는 옮긴 항목의 id 들이고, destination.position 은 .before(id) 또는 .end 다.

difference.apply(to:) 는 SwiftUI 가 주는 메서드가 아니다. 세션에서 직접 쓴 helper 다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import OrderedCollections // from https://github.com/apple/swift-collections

extension ReorderDifference where CollectionID == ReorderableSingleCollectionIdentifier {
    func apply(to values: inout [some Identifiable<ItemID>]) {
        var dictionary = OrderedDictionary(uniqueKeys: values.map { $0.id }, values: values)
        let destinationOffset: Int? = switch destination.position {
        case .before(let destination):
            dictionary.keys.firstIndex(of: destination)
        case .end:
            nil
        }
        dictionary.move(keys: sources, to: destinationOffset ?? values.endIndex)
        values = dictionary.values.elements
    }
}

배열을 id 가 key 인 OrderedDictionary 로 바꾸고, sources 에 해당하는 key 들을 목적지 offset 으로 옮긴 다음 다시 배열로 꺼낸다. 목적지가 .end 면 배열 끝으로 보낸다. OrderedDictionary 는 swift-collections package 의 OrderedCollections module 에 있다. 이 글에서는 swift-collections 를 package 의존성으로 추가해서 빌드했다.

이 API 는 List 전용이 아니다. 어떤 container 에도 같은 코드가 붙는다. sticker 를 grid 로 보여 주는 화면은 List 를 LazyVGrid 로 바꾸기만 하면 된다.

1
2
3
4
5
6
7
8
9
LazyVGrid(columns: [GridItem(.adaptive(minimum: 80))]) {
    ForEach(stickers) { sticker in
        StickerListItemView(sticker: sticker)
    }
    .reorderable()
}
.reorderContainer(for: Sticker.self) { difference in
    difference.apply(to: &stickers)
}

세션 코드는 LazyVGrid { } 로 columns 를 생략했다. 그대로는 빌드되지 않아서 columns 를 채웠다. 순서를 바꾸는 코드는 List 때와 글자 하나 다르지 않다.

watchOS 에서도 이 API 로 처음으로 reordering 을 쓸 수 있게 됐다. 여러 collection 사이를 옮기는 것 같은 나머지 기능은 code-along 세션 Build powerful drag and drop in SwiftUI 에서 다룬다.


List 밖에서 쓰는 swipe action

iPhone 에서는 화면 아래 sheet 에 sticker 목록이 있고, swipe 로 지울 수 있다. List 에서는 원래 되던 일이다.

1
2
3
4
5
6
7
8
List {
    ForEach(stickers) { sticker in
        StickerListItemView(sticker: sticker)
            .swipeActions {
                DeleteButton(sticker: sticker)
            }
    }
}

항목 모양을 더 자유롭게 꾸미려고 LazyVStack 으로 바꿔도 이제 swipe action 이 그대로 동작한다.

1
2
3
4
5
6
7
8
9
10
11
ScrollView {
    LazyVStack {
        ForEach(stickers) { sticker in
            StickerListItemView(sticker: sticker)
                .swipeActions {
                    DeleteButton(sticker: sticker)
                }
        }
    }
}
.swipeActionsContainer()

swipeActionsContainer 로 swipe action 조율하기

swipeActionsContainer() 는 scroll view 안에 있는 항목들의 swipe action 을 조율한다. List 가 안에서 해 주던 일을 밖으로 꺼낸 것이다. 항목에는 예전과 같은 swipeActions 를 붙이고, 그 항목들을 담은 scroll view 에 이 modifier 를 하나 붙인다.


item binding 으로 띄우는 dialog

사진 위에 놓은 sticker 에는 context menu 가 있고, Delete 를 누르면 확인 dialog 가 뜬다. confirmationDialog 가 이제 sheet 와 같은 item binding 패턴을 지원한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct StickerCanvasView: View {
    var stickers: [Sticker]
    @State private var stickerToDelete: Sticker?

    var body: some View {
        ZStack {
            ForEach(stickers) { sticker in
                PlacedStickerView(sticker: sticker)
                    .contextMenu {
                        // ...
                    }
            }
        }
        .confirmationDialog(
            "Delete?", item: $stickerToDelete
        ) { sticker in
            DeleteStickerButton(sticker)
        }
    }
}

context menu 의 Delete 버튼은 stickerToDelete 에 지금 sticker 를 넣는다. 값이 nil 이 아니게 되는 순간 dialog 가 뜨고, closure 는 optional 이 벗겨진 sticker 를 받는다.

confirmationDialog 의 item binding 으로 dialog 띄우기

[confirmationDialog(:item:titleVisibility:actions:)](https://developer.apple.com/documentation/swiftui/view/confirmationdialog%28:item:titlevisibility:actions:%29){:target=”_blank”} 는 optional 값의 binding 하나로 dialog 를 띄운다. 예전에는 isPresented 용 Bool 과 presenting 에 넘길 값을 따로 두어야 했다. 두 state 가 어긋날 여지가 없어진다.

alert 도 같은 형태를 지원한다. modifier 이름만 바꾸면 된다.

1
2
3
4
5
.alert(
    "Delete?", item: $stickerToDelete
) { sticker in
    DeleteStickerButton(sticker)
}

alert 의 item binding 으로 alert 띄우기

[alert(:item:actions:)](https://developer.apple.com/documentation/swiftui/view/alert%28:item:actions:%29){:target=”_blank”} 는 confirmationDialog 와 같은 패턴이다. 옛 alert(item:content:) 와는 다른 API 다. 옛 것은 Alert 값을 돌려주는 방식이고 deprecated 상태다.


data flow 와 performance

마지막 장의 개선은 대부분 이미 쓰고 있는 API 가 코드 변경 없이 좋아지는 종류다. AsyncImage 의 cache, @State 의 초기화 방식, 그리고 compiler 의 type check 속도 세 가지다.


AsyncImage 의 HTTP cache

AsyncImage 는 지금까지 이미지를 memory 에 들고 있지 않았다. 스크롤을 내렸다가 다시 올리면 화면에 다시 나타나는 이미지를 또 받아 왔다.

2027 releases 에서는 AsyncImage 가 표준 HTTP caching 을 지원한다. 서버가 보낸 cache header 를 따라 기본으로 cache 하고, 모든 앱에 자동으로 적용된다. 코드를 바꿀 필요가 없다.

Xcode 27 로 빌드한 앱은 다운로드 방식을 직접 조정하는 새 API 도 쓸 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Observable class StickerStore {
    static let imageSession: URLSession = {
        let config = URLSessionConfiguration.default
        config.urlCache = URLCache(
            memoryCapacity: 64 * 1024 * 1024,
            diskCapacity: 256 * 1024 * 1024)
        return URLSession(configuration: config)
    }()
}

ForEach(pets) { pet in
    AsyncImage(request: URLRequest(
        url: pet.imageURL,
        cachePolicy: .returnCacheDataElseLoad)
    )
}
.asyncImageURLSession(StickerStore.imageSession)

조정하는 범위가 둘로 나뉜다.

AsyncImage 의 request 로 요청별 설정하기

AsyncImage(request:) 는 URL 대신 URLRequest 를 받는다. cache policy 처럼 요청 하나에 대한 설정을 여기에 담는다. 위 코드의 .returnCacheDataElseLoad 는 cache 에 있으면 만료 여부와 상관없이 그것을 쓰고, 없을 때만 받아 온다.

asyncImageURLSession 으로 session 바꾸기

[asyncImageURLSession(:)](https://developer.apple.com/documentation/swiftui/view/asyncimageurlsession%28:%29){:target=”_blank”} 은 하위 view 의 AsyncImage 가 쓸 URLSession 을 지정한다. 더 큰 cache 처럼 오래 유지되는 설정은 session 쪽에 둔다. 위 코드는 memory 64MB, disk 256MB 짜리 URLCache 를 가진 session 을 만들어 넘긴다.


lazy 하게 바뀐 State

@Observable class 를 @State 에 담는 것은 흔한 패턴이다.

1
2
3
4
5
6
7
8
9
10
11
@Observable class StickerStore { }

struct StickerStoreView: View {
    // store is now lazily initialized, only
    // created once for the lifetime of the view
    @State private var store = StickerStore()

    var body: some View {
        // ...
    }
}

StickerStoreView 가 처음 초기화될 때 StickerStore instance 가 만들어져 state 에 저장되고, view 의 lifetime 동안 유지된다. 문제는 그 뒤였다.

  • 이전 release: 부모 view 가 갱신되어 StickerStoreView 가 다시 초기화될 때마다 StickerStore() 가 또 실행됐다. state 에는 여전히 처음 instance 가 들어 있으므로 새로 만든 것은 그냥 버려졌다. 재초기화마다 이 낭비가 반복됐다
  • 2027 releases: @State 에 저장한 class 는 lazy 하다. 처음 한 번만 초기화되고, 이후 재초기화에서는 새 instance 를 만들지 않는다

이것이 가능해진 이유는 State 가 DynamicProperty 에서 macro 로 바뀌었기 때문이다. SDK 에도 macro State() 가 선언되어 있다. 이 동작은 @Observable 이 처음 나온 iOS 17, macOS 14 와 같은 해의 release 까지 back port 됐다.


State macro 로 생기는 build error

macro 로 바뀌면서 기존 코드가 빌드되지 않는 경우가 생길 수 있다. 세션이 드는 예는 기본값을 준 @State 에 init 에서 다시 대입하는 코드다.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct StickerPageView: View {
    @State private var page = StickerPage()
    let title: String

    init(title: String) {
        self.page = StickerPage(title: title) // Variable 'self.title' used before being initialized
        self.title = title
    }

    var body: some View {
        // ...
    }
}

Xcode 27.0 에서 빌드해 보니 세션과 같은 자리에서 에러가 났다.

1
error: variable 'self.title' used before being initialized

에러 메시지가 가리키는 것은 title 이지만 원인은 page 의 기본값이다. 해결은 필요 없는 기본값을 지우는 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
struct StickerPageView: View {
    @State private var page: StickerPage // Removed default value to fix error
    let title: String

    init(title: String) {
        self.page = StickerPage(title: title)
        self.title = title
    }

    var body: some View {
        // ...
    }
}

이 형태는 빌드된다. 세션은 State macro 가 코드에 주는 다른 영향은 문서를 보라고 하고 넘어간다.


type check 가 느렸던 이유

view 가 깊게 중첩된 앱이라면 이 에러를 본 적이 있을 것이다.

1
The compiler is unable to type-check this expression in reasonable time

세션은 Section 안에 Group, 그 안에 ForEach 가 있는 view 로 원인을 설명한다.

  1. compiler 는 먼저 Section 의 어느 overload 를 쓸지 골라야 한다. Section 은 View 를 만드는 builder 로도, TableRowContent 를 만드는 builder 로도 초기화할 수 있다. 어느 쪽인지 알려면 둘 다 시도해 봐야 한다
  2. Section 의 builder 가 돌려주는 것은 Group 이다. Section 이 어떤 content 를 만드는지는 안쪽 Group 의 content 타입을 알아야 정해진다. Group 은 선택지가 더 많다
  3. 그 안의 ForEach 도 자기 선택지를 따로 갖고 있고, 전부 확인해야 한다

출처: WWDC26 - What’s new in SwiftUI

아직 실제 content 에는 닿지도 않았다. 중첩이 한 단계 깊어질 때마다 시도할 경로가 곱으로 늘어난다. 그런데 코드를 쓴 사람은 이 Section, Group, ForEach 가 전부 view 를 만든다는 것을 이미 안다. 유효한 경로는 하나뿐이다.


ContentBuilder 란?

ContentBuilder 는 여러 builder 타입을 하나로 합친 result builder 다. builder 가 자기가 만드는 타입에 묶이지 않고 content 를 조립만 한다는 것이 발상이다.

2027 releases 에서는 가장 흔히 쓰는 builder 들이 initializer 하나를 공유한다. overload 가 여러 개가 아니므로 compiler 가 갈 길이 하나만 남는다.

출처: WWDC26 - What’s new in SwiftUI

SDK 에서도 확인된다. alert 나 confirmationDialog 의 actions closure, DocumentGroup 의 editor closure 가 전부 @ViewBuilder 가 아닌 @ContentBuilder 로 선언되어 있다.

세션이 밝힌 특징은 세 가지다.

  • SwiftUI 의 모든 API 에서 builder 를 통합하기 위한 한 단계다. 이번에 전부 바뀐 것은 아니다
  • 내부적으로는 기존 ViewBuilder 가 발전한 형태라서 minimum deployment target 이 무엇이든 쓸 수 있다
  • Xcode 27 로 빌드하면 type check 성능이 크게 좋아진다. 2027 releases 가 대상이든 이전 release 가 대상이든 마찬가지다

직접 쓸 때는 @ViewBuilder 자리에 그대로 쓴다.

1
2
3
4
@ContentBuilder
func stickerLibraryView() -> some View {
  // ...
}

body 에 Text 하나를 넣어서 빌드되는 것을 확인했다.


Xcode 27 의 agent skill

Xcode 27 에는 2027 releases 의 새 기능을 적용하는 일을 돕는 agent skill 두 가지가 들어 있다.

  • SwiftUI Specialist Skill: SwiftUI 의 best practice 를 따르도록 돕는다
  • What’s New In SwiftUI Skill: 2027 releases 의 새 API 를 적용하는 과정을 안내한다

둘 다 Xcode 27 의 Coding Assistant 에서 쓸 수 있다. 다른 도구에서 쓰려면 xcrun agent skills export 명령으로 내보낸다. markdown 파일이 만들어지고, 이것을 자기 workflow 에 가져다 쓴다. --output-dir 로 위치를 정하면 skill 마다 directory 가 하나씩 생기고 그 안에 SKILL.md 와 references directory 가 들어간다. Xcode 27.0 에서는 10개가 나온다: swiftui-specialist, swiftui-whats-new-27, uikit-app-modernization, app-intents-specialist, app-intents-whats-new-27, building-document-based-swiftui-applications, adopt-c-bounds-safety, audit-xcode-security-settings, modernize-tests, device-interaction. 위의 두 skill 은 swiftui-specialist 와 swiftui-whats-new-27 이다.


정리

세션이 마지막에 권하는 순서는 이렇다.

  1. 프로젝트를 Xcode 27 로 2027 releases 대상으로 빌드해서 바뀐 look and feel 을 확인한다
  2. document 기반 앱이라면 새 Document API 로 무엇이 좋아지는지 살펴본다
  3. Xcode 27 의 SwiftUI agent skill 로 새 API 와 best practice 를 적용한다

내용을 “해야 하는 일” 기준으로 다시 나누면 다음과 같다.

구분항목
아무것도 안 해도 되는 것새 Liquid Glass, iPad 비활성 window 표시, menu bar 아이콘 최소화, AsyncImage HTTP cache, lazy 한 @State, type check 속도
확인이 필요한 것iPhone 앱 resize 대응 (UIKit 혼용 앱), 기본값을 준 @State 에 init 에서 대입하는 코드
새로 쓸 수 있는 것prominent tab, toolbar 우선순위와 overflow menu, bar 최소화, 새 Document API, reorderable container, swipeActionsContainer, item binding dialog, asyncImageURLSession

세션 코드를 그대로 옮겼을 때 빌드되지 않은 곳도 모아 둔다. Xcode 27.0 기준이다.

  • toolbarMinimizeBehavior 는 toolbarMinimizationBehavior 로 써야 한다
  • writableDocumentTypes 는 writableContentTypes 로 써야 한다
  • struct Writer<Snapshot> 는 generic parameter 를 빼야 writer(configuration:) 의 반환 타입으로 쓸 수 있다
  • DocumentGroup 에 넘기는 document 는 Document protocol 을 명시적으로 따라야 한다

실제 프로젝트에 가져갈 점도 적어 둔다.

  • @State private var x = X() 로 두고 init 에서 다시 대입하는 view 가 있는지 먼저 찾아본다. Xcode 27 로 올리자마자 build error 가 되는 유일한 항목이다
  • toolbar 에 버튼이 많은 화면은 iPhone 폭에서 무엇이 overflow menu 로 들어가는지 확인하고, 꼭 보여야 하는 것에만 visibilityPriority(.high) 나 topBarPinnedTrailing 을 준다. 전부 high 로 주면 의미가 없다
  • isPresented 와 선택된 값을 state 두 개로 관리하던 삭제 확인 dialog 는 item binding 하나로 줄일 수 있다
  • 이미지 cache 때문에 따로 넣은 library 나 직접 만든 cache 가 AsyncImage 를 감싸는 수준이었다면 걷어낼 수 있는지 볼 만하다

관련 글


참고자료

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