在 SwiftUI 视图中设置计算 属性 不会编译

setting computed property in a SwiftUI view doesn't compile

尝试在 SwiftUI 视图中设置计算的 属性 会出现编译器错误 "Cannot assign to property: 'self' is immutable"。
我必须如何调用 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
    }
  }
}

这就是为什么您的视图中已经有了 @State 属性 包装器。

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

您可以直接从您的代码中更改 s,因为 s 是用 @State 包装的。

这与上面的功能等价

struct Test: View{
    let s = State<String>(initialValue: "alfa")
    var body: some View {
        VStack {
            Text("\(s.wrappedValue)")
                .onTapGesture {
                    self.s.wrappedValue = "beta"
            }
        }
    }
}

或者如果需要绑定

struct Test: View{
    let s = State<String>(initialValue: "alfa")
    var body: some View {
        VStack {
            TextField("label", text: s.projectedValue)
        }
    }
}

啊哈...我明白了。只需使用非变异集

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