在 Swift 中的 If 语句中设置 @State var

Set a @State var inside an If statement in Swift

我正在尝试在 :View 类型的结构内部的 If 语句中设置 @State var 的值,如下所示:

struct Name: View {
  @State someVar: Int = 0
    var body: some View {
      VStack {
        if this > that {
          someVar = 1

但是当我这样做时,我得到了错误:“Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols”。如果我使用 class 方法来满足我的需要,就像这样:

    if this > that {       
      someClass.doIt()
    }

我得到同样的错误。

正确的做法是什么?

你不能把这样的逻辑代码放在你的 body 中——你所能拥有的只有输出视图的代码。

所以,你可以这样做:

var body: some View {
  if this > that {
    Text("This")
  } else {
    Text("That")
  }
}

因为这会导致视图 (Text) 被渲染。不过,在您的示例中,您只是在做作业。

这必须在单独的函数中或在视图中直接呈现的内容之外的闭包中完成。

所以:

func testThisThat() {
  if this > that {
   someVar = 1
  }
} 

var body: some View {
  Button(action: {
   testThisThat()
  }) {
   Text("Run test")
  }
}

在上面,您的逻辑 运行 在视图层次结构之外的闭包中,并且 Button 呈现给视图。

如果您提供更多有关您尝试执行的操作的具体信息,也许可以澄清答案,但这就是错误的根源。

按照评论中的建议,你也可以在onAppear中运行逻辑代码,像这样:

var body: some View {
  VStack {
   //view code
  }.onAppear {
   //logic
    if this > that {
      someVar = 1
    } 
  }
}