Search code examples
swiftswiftuicomputed-properties

setting computed property in a SwiftUI view doesn't compile


Trying to set the computed property s in a SwiftUI view gets compiler error "Cannot assign to property: 'self' is immutable".
How do I have to I call the setter?

struct Test: View{
  @State var _s = "test"
  @State var _s2 = true
  private var s : String
  { get { _s }
    set (new)
    { _s = "no test"
      _s2 = false
      // do something else
    }
  }

  var body: some View
  { Text("\(s)")
    .onTapGesture {
      self.s = "anyting"  // compiler error
    }
  }
}

Solution

  • Aha... I see. Just use non mutating set

      private var s : String
      { get { _s }
        nonmutating set (new)
        { _s = "no test"
          _s2 = false
          // do something else
        }
      }