Reputation: 1
I want control the passed value to Binding for custom initializing, I am using this down code, xcode throw me this:
need help to solve the problem, thanks for help.
import SwiftUI
struct ContentView: View {
@State private var int: Int = Int()
var body: some View {
BindingView(int: $int)
}
}
struct BindingView: View {
@Binding var int: Int
init(int: Binding<Int>) {
if int == 0 { // <<: Here
_int = 100 // <<: Here
}
else {
_int = int
}
}
var body: some View {
Text(int.description)
}
}
Upvotes: 0
Views: 65
Reputation: 52387
You can't access Int
directly like that for comparison, since it's a @Binding. Instead, you'll want to access its wrappedValue
:
You're also running into a couple funny things just from naming your input parameter (int
) the same as your stored property, but it's easily fixable. Here's one variation:
struct BindingView: View {
@Binding var int: Int
init(int: Binding<Int>) {
if int.wrappedValue == 0 { // <<: Here
int.wrappedValue = 100 // <<: Here
}
self._int = int
}
var body: some View {
Text(int.description)
}
}
Note that there's some tricky subtlety here: @Binding
lets you directly access the underlying value, while with Binding<Int>
you have to use the wrappedValue
property.
Upvotes: 1