I believe that the use of @AppStorage or @SceneStorage is causing view equality to fail in a way that @State does not. This is unexpected and can lead to much unneeded computation and wasted cycles.
Comments?
import SwiftUI
struct InnerView: View {
// Using @State, the toggle starts at false whenever you start the app.
// Using @AppStorage can let the app remember what the value of the toggle was.
// But if we comment out the @State version and uncomment the @AppStorage
// version, now we are hit by excessive recomputation.
@State var initialValue = false
// If you comment out the above @State variable and uncomment the @AppStorage
// version below, although the starting toggle state is preserved, we have a serious issue:
// the function someText() is called while dragging the slider in ContentView.
// I believe that view equality on InnerView is failing due to the AppStorage
// property wrapper in a way it does not for the State property wrapper.
//@AppStorage("initialValue") var initialValue = false
func someText() -> String {
print("someText called: \(Date())")
return "Blah"
}
var body: some View {
VStack {
Toggle("Toggle: ", isOn: $initialValue)
Text(someText())
}
}
}
struct ContentView: View {
@State var sliderValue = 0.0
var body: some View {
VStack {
Slider(value: $sliderValue)
InnerView()
}.padding()
}
}
young
(rtSwift)
2
Something strange, if you add _printChanges():
var body: some View {
let _ = Self._printChanges()
VStack {
Toggle("Toggle: ", isOn: $initialValue)
Text(someText())
}
}
It show @self is the change, not initialValue.
I have not heard of _printChanges() but it sounds extremely useful! What exactly does it tell me?
2 Likes
tera
5
This looks extremely useful. Thanks for sharing for those of us who are not on Twitter.
Interestingly by searching for "_printChanges" on Apple site I found there is a SwiftUI Q&A session tomorrow Dec 14. You'd need to register to join it.
PS. I believe we need a place dedicated to swiftUI questions. More alive than Apple Developer Forums, something like this discourse forum but dedicated to swiftUI. I can see a few categories here in "Related Projects", quite a few with just a few messages there and but SwiftUI is not one of the categories. Could we establish SwiftUI as one of the subcategories of this forum?