DynamicProperty in SwiftUI

Pawan Manjani
2 min readAug 27, 2024

--

In SwiftUI, we have property wrappers like @State, @StateObject, and @AppStorage. Additionally, we can create our own custom property wrappers.

@propertyWrapper
struct Uppercased {
@State var wrappedValue: String
var projectedValue: Binding<String> {
Binding(
get: {
return wrappedValue.uppercased()
},
set: { newValue in
wrappedValue = newValue.uppercased()
}
)
}
}

Which we can use in our SwiftUI like below:

@uppercased var name: String = ""

and the full code of the SwiftUI view is below:

struct ContentView: View {
@Uppercased var name: String = ""
var body: some View {
VStack {
Text("Hello, \(name)")
TextField("Enter here", text: $name)
}
.padding()
}
}

I hope if we run this code and our new changes will be updated to Text view runtime. Let’s run the code

As we can see, the name is not appearing when we enter it.

Here comes DynamicProperty to help us.

Just conform DynamicProperty protocol to the struct of property wrapper like below:

struct Uppercased: DynamicProperty { //Here
@State var wrappedValue: String
var projectedValue: Binding<String> {
Binding(
get: {
return wrappedValue.uppercased()
},
set: { newValue in
wrappedValue = newValue.uppercased()
}
)
}
func update() { // This is called when the view will evaluate its body.
print("update called")
}
}

So after adding this let’s run the code and see the output

You can include @StateObject properties within your property wrapper to trigger updates in your views.

Please like and follow for more

Thanks for reading, Happy Coding 💻

--

--

Responses (2)