32
votes

Let's say that I am making a custom input element that looks like this:

struct CustomInput : View {
    @Binding var text: String
    var name: String

    var body: some View {
        TextField(name, text: $text)
            .modifier(InputModifier())

    }
}

Currently, when I instantiate this view I'm required to pass both text and name names to arguments. I want to be able to make the name argument optional, like in the example below.

 CustomInput("Some name", $text)

Typically I'd use an init method for this. But I'm not sure how to handle property wrappers like @Binding in the init function.

Any ideas on how I can achieve this?

1

1 Answers

55
votes

You can write your initializer like this:

struct CustomInput : View {
    @Binding var text: String
    var name: String

    init(_ name: String, _ text: Binding<String>) {
        self.name = name

        // Beta 3
        // self.$text = text

        // Beta 4
        self._text = text
    }

    var body: some View {
        TextField(name, text: $text)
    }
}