Skip to content

SwiftUI Property Wrappers

There’s no tl;dr for this topic since it does require some foundational knowledge. Donny Wals wrote up a great article at https://swiftuipropertywrappers.com on the differences and how to choose the right one for the occasion.

@State

@State property wrappers are great when no outside view will access the data hence should be marked private as follows @State private var username

struct StateExampleView: View {
    @State private var dollarsInMyPocket = 10

    var body: some View {
        VStack {
             Text("Dollars in my pocket $\(dollarsInMyPocket)")
            
            Button("Reality") {
                    dollarsInMyPocket -= 1
                  }
        }
        .padding()
    }
}

@Binding

Passing data from a parent to a child view in a really simple heirarchy. Here’s a copy + paste from Donny’s website/post:

struct StateView: View {
  @State private var intValue = 0

  var body: some View {
    VStack {
      Text("intValue equals \(intValue)")

      BindingView(intValue: $intValue)
    }
  }
}

struct BindingView: View {
  @Binding var intValue: Int

  var body: some View {
    Button("Increment") {
      intValue += 1
    }
  }
}

@EnvironmentObject

As you can see @Binding is nice but do you really want to pass it down to *all* the child views? Nope. This is where @EnvironmentObject comes in. Again, copy paste from Dony’s website/post

struct MyApp: App {
  @StateObject var dataProvider = DataProvider()

  var body: some Scene {
    WindowGroup {
      EnvironmentUsingView()
        .environmentObject(dataProvider)
    }
  }
}

struct EnvironmentUsingView: View {
  @EnvironmentObject var dependency: DataProvider

  var body: some View {
    Text(dependency.currentValue)
  }
}

These property wrappers become the building blocks of most the apps.

Leave a Reply

Your email address will not be published. Required fields are marked *