Skip to content

Commit cf1f65e

Browse files
committed
reduce cost of init with task modifier
1 parent f93688e commit cf1f65e

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

Guide.docc/Articles/MakeInitializerLowCost.md

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,28 @@ struct DogRootView: View {
2929
この例では`DogRootView`のイニシャライザで`FetchModel`がイニシャライズされます。
3030
`FetchModel`のイニシャライザで処理に時間のかかる`fetchDogs`が同期的に呼び出されているため、`DogRootView`のイニシャライザが高コストとなっています。
3131

32-
### `.task`でイニシャライザのコストを下げる
33-
xxx
32+
### task modifierでイニシャライザのコストを下げる
33+
この場合は、`fetchDogs``async`にし、`.task`で非同期にデータを読み込むことでイニシャライザを低コストにします。
34+
35+
```swift
36+
struct DogRootView: View {
37+
@State private var model = FetchModel()
38+
39+
var body: some View {
40+
DogList(model.dogs)
41+
.task { await model.fetchDogs() }
42+
}
43+
}
44+
45+
@Observable class FetchModel {
46+
var dogs: [Dog]
47+
48+
init() { }
49+
50+
func fetchDogs() async {
51+
// Takes a long time
52+
}
53+
}
54+
```
55+
56+
> WWDC23 Demystify SwiftUI performance [12:20~](https://developer.apple.com/videos/play/wwdc2023/10160/?time=740)

0 commit comments

Comments
 (0)