I know that State wrappers are for View and they designed for this goal, but I wanted to try build and test some code if it is possible, my goal is just for learning purpose,
I have 2 big issues with my code!
Xcode is unable to find T.
How can I initialize my state?
import SwiftUI
var state: State<T> where T: StringProtocol = State(get: { state }, set: { newValue in state = newValue })
struct ContentView: View {
var body: some View {
Text(state)
}
}
Update: I could do samething for Binding here, Now I want do it for State as well with up code
import SwiftUI
var state2: String = String() { didSet { print(state2) } }
var binding: Binding = Binding.init(get: { state2 }, set: { newValue in state2 = newValue })
struct ContentView: View {
var body: some View {
TextField("Enter your text", text: binding)
}
}
If I could find the answer of my issue then, i can define my State and Binding both outside of View, 50% of this work done and it need another 50% for State Wrapper.
New Update:
import SwiftUI
var state: State<String> = State.init(initialValue: "Hello") { didSet { print(state.wrappedValue) } }
var binding: Binding = Binding.init(get: { state.wrappedValue }, set: { newValue in state = State(wrappedValue: newValue) })
struct ContentView: View {
var body: some View {
Text(state) // <<: Here is the issue!
TextField("Enter your text", text: binding)
}
}

T? Currently yourTis constrained tostringProtocol, but how will you satisfy concrete type for T? T doesn’t know whom to communicate with. Also you are passingState<String>in Text, which is incorrect. Another thing initialiser forStatedoesn’t have get and set @escaping blocks, unlike Bindings.Stateobject outside view likevar state = State(wrappedValue: “foo”), and you can useprojectedValueasBindinginside views, andwrappedvalue to access actual value. That’s one way without going generic. Is generic a must requirement?State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update. So, I was wrong don’t use it.