Manipulating binding variables in SwiftUI

Suppose I have a string that’s binding:

@Binding var string: String

But, I want to manipulate that string, and then pass it to a child view.

struct ViewOne: View {
    @State var string: String = "Hello"
    
    var body: some View {
        ViewTwo(string: string + " World") // this is invalid, as ViewTwo requires Binding<String>
    }
}

struct ViewTwo: View {
    @Binding var string: String
    
    var body: some View {
        Text(string)
    }
}

How should I go about manipulating that string, such that it will update the UI when the state changes? Let’s assume that I want to re-use ViewTwo for different components, and so I would want to manipulate the string before it is passed to the view.

A computed variable doesn’t work, as it isn’t Binding

private var fixedString: String {
    return string + " World"
}

And I don’t want to create a binding variable, because the setter makes no sense in this context

private var fixedString: Binding<String> {
    Binding<String> (
        get: {
            string + " World"
        }, set: {
            // this function doesn't make sense here - how would it update the original variable?
        }
    )
}

Am I just using @State and @Binding wrong?

>Solution :

Just remove the @Binding inside ViewTwo:

struct ViewTwo: View {
    var string: String /// no need for the `@Binding`!
    
    var body: some View {
        Text(string)
    }
}

SwiftUI will update ViewTwo even if you don’t have the @Binding (it basically re-renders the entire body whenever a @State or @Published var gets changed).

You only need Bindings when you need to update/set the original @State or @Published property. In that case you’d add something like the var fixedString: Binding<String> in your question.

Leave a Reply