Adding setter to @State property impossible?

58 views Asked by At

If I change @State var pan: Int to this:

  @State var pan: Int {
    set(x) {
      self.pan = min(max((x), -50), 50)
    }
    get {
      return self.pan
    }
  }

I get the error: Cannot apply property wrapper to computed property. The error goes away when I remove the @State wrapper.

But then I get the message, Cannot assign to property: 'self' is immutable

Is there some way that I can get both?

2

There are 2 answers

2
vadian On

Long story short: No, you can't get both.

Why not simply a second (computed) property

@State private var pan = 0

var panWrapper: Int {
    get { pan }
    set { pan = min(max((newValue), -50), 50) }
 }

Or alternatively a @Binding

let panBinding = Binding {
    pan
} set: {
    pan = min(max(($0), -50), 50) }
}
2
malhal On

Sure, something like this:

struct Content {
    var pan: Int {
    set {
      _pan = min(max((newValue), -50), 50)
    }
    get {
      return _pan
    }
  }
   var _pan: Int = 0

   //mutating func otherLogic(){}
}


struct ContentView : View {

    @State var content = Content()   

    // use content.pan
...