Last active
April 22, 2024 14:58
-
-
Save eecs441staff/8011b7f58dbbfdf04b23604320595e4c to your computer and use it in GitHub Desktop.
SwiftUI @State emulation with SwiftUI memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UM EECS 441 | |
import SwiftUI | |
@propertyWrapper | |
struct SimpleState<T>: DynamicProperty { | |
private var _state: State<T> // references SwiftUI memory outside of struct | |
var wrappedValue: T { | |
get { _state.wrappedValue } // accesses reference to SwiftUI memory | |
nonmutating set { _state.wrappedValue = newValue } // no change to reference | |
} | |
var projectedValue: Binding<T> { | |
Binding( | |
get: { wrappedValue }, | |
set: { wrappedValue = $0 } | |
) | |
} | |
init(wrappedValue: T) { | |
_state = State(wrappedValue: wrappedValue) // allocate space in SwiftUI memory | |
} // also comes with subscription! | |
} | |
struct ChildView: View { | |
@Binding var count: Int | |
var body: some View { | |
Button("+1") { count += 1 } | |
} | |
} | |
struct ContentView: View { | |
@SimpleState var count = 0 | |
var body: some View { | |
VStack { | |
Text("\(count)").font(.system(size: 28)) | |
ChildView(count: $count) | |
} | |
.font(.system(size: 28)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment