File tree Expand file tree Collapse file tree 1 file changed +25
-2
lines changed Expand file tree Collapse file tree 1 file changed +25
-2
lines changed Original file line number Diff line number Diff line change @@ -29,5 +29,28 @@ struct DogRootView: View {
29
29
この例では` DogRootView ` のイニシャライザで` FetchModel ` がイニシャライズされます。
30
30
` FetchModel ` のイニシャライザで処理に時間のかかる` fetchDogs ` が同期的に呼び出されているため、` DogRootView ` のイニシャライザが高コストとなっています。
31
31
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 )
You can’t perform that action at this time.
0 commit comments