【问题标题】:How to initialize a @State variable inside a view [duplicate]如何在视图中初始化@State变量[重复]
【发布时间】:2021-09-13 17:23:54
【问题描述】:

我有一个用项目列表初始化的视图,然后在初始化过程中,我们需要随机选择一个项目。像这样的:

struct ItemsView: View {

    var items:[Item]
    @State var current:Item?

    init(items:[Item] = []) {
        self.items = items
        if items.count > 0 {
            let index = Int.random(in: 0..<items.count)
            self.current = items[index] // doesnt work
        }
        if current != nil {
            print("init with", self.items.count, "items. Chose", current!)
        }
    }

    // ...
}

ItemsVew 的工作是一次随机显示一个项目,所以我们从随机选择一个项目开始,但据我所知,self.current = items[index] 实际上并没有做任何事情,原因是我不明白。所以要么我在做一些愚蠢的事情,要么我正在考虑如何以某种方式错误地解决这个问题。

那么如何在 init 函数中初始化一个 State 变量。我试过了:

self.current = State(initialValue: items[index])

但这只会触发编译器错误。那么我们如何选择一个将在视图显示时使用的初始项呢?

Cannot assign value of type 'State<Item>' to type 'Item'

我做错了什么?

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    因为@State 是一个属性包装器,所以您希望分配给底层变量本身,而不是包装的值类型(在本例中为Item?)。

    self._current = State(initialValue: items[index])
    //   ^ note the underscore
    

    原始Swift Evolution SE-0258 提案文档中提供了这方面的最佳文档。

    【讨论】:

      【解决方案2】:

      @Stateproperty wrapper,因此您需要将Item? 对象分配给current 属性,这就是编译器给您错误的原因。因此,只要您传递的 items 数组不为空,这应该可以按预期工作。此外,我鼓励您在 items 数组上使用 randomElement() 方法,而不是生成随机索引。

      struct ItemsView: View {
      
          var items: [Item]
          @State var current: Item?
      
          init(items: [Item] = []) {
              self.items = items
              self.current = items.randomElement()
              if let item = current {
                  print("init with", self.items.count, "items. Choose", item)
              }
          }
      
          // ...
      }
      

      【讨论】:

      • 这实际上不起作用,因为 SwiftUI 不允许您在初始化程序中更改 state 属性的值。您必须初始化底层状态属性本身,即 self._current.
      • 怎么样?我刚刚检查了一下,我能够在初始化中为 @State 属性分配一个值而没有任何错误
      • 是的,它没有给出错误,但也没有设置值。您应该会发现 State 属性仍然是您为其设置的默认值。
      猜你喜欢
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多