Should we extend propertyWrapper capability to variables and parameters?

I think the propertyWrapper capability should extend to the general variables, like parameters in function.

For example, currently we should write:

    func backgroundAndBorder(isSelected: Binding<Bool>) -> some View {
        self
            .background(  isSelected.wrappedValue ? Color.white : Color.black).onTapGesture { isSelected.wrappedValue.toggle() })
            .border(Color.primary)
    }

but if we extend the propertyWrapper capability to variables and parameters
we could write:

    func backgroundAndBorder(@Binding isSelected: Bool) -> some View {
        self
            .background( isSelected ? Color.white : Color.black).onTapGesture { isSelected.toggle() })
            .border(Color.primary)
    }

Also it could use for value transformation
we may write:

    let intValue = 1234 // Int
    let stringValue = "1234" // String

    @StringIntWrapper let wrapper = stringValue // StringIntWrapper, pass stringValue into the new StringIntWrapper as its wrapped value

    $wrapper == intValue // true, using the projected value of StringIntWrapper
    wrapper == stringValue // true, using the wrapped value of StringIntWrapper

PropertyWrapper could be modeled as a general value transfer mechanism.

4 Likes

I believe local variable support was intended to eventually be added, but I haven't seen parameter support discussed. I think it makes sense in both cases, but since wrappers are still being implemented (composition is just arriving in Swift 5.2), those will likely come later.

2 Likes

I don‘t think we‘d get the ability for parameters as we already dropped support for var for parameters, which would be a requirement for property wrappers.

Support for local variables will eventually be implemented.

@anthonylatsis has a WIP PR that implements lazy support for local variables, which should allow us to support @propertyWrapper on local variables too.

2 Likes

How would the (unofficial) static subscript with “enclosingInstance” work for local variables? Or would some property wrappers just not work in local contexts?

In SE-30, I had it so that local and global variables had an "enclosing instance" of type (). I think that would work with property wrappers as well.

2 Likes