【问题标题】:Why can I not use append to create an array in SwiftUI为什么我不能在 SwiftUI 中使用 append 创建数组
【发布时间】:2020-11-13 12:45:19
【问题描述】:

我有以下简单的例子:

struct Test {
    var id:Int
    var text:String
}
struct ContentView: View {

    var array = [Test]()

    var body: some View {
        VStack{
            
            ForEach(0...3, id:\.self){ key in
                let test = Test(id: key, text: "Testing")
                array.append(test)
          
            }
}}

我收到错误消息: 类型 '()' 不能符合 'View';只有结构/枚举/类类型可以符合协议 如果我删除 array.append 行,那么错误消息就会消失。所以,在 Swift 中这会很好用,但在 SwiftUI 中这似乎是不同的。有人可以解释一下为什么以及如何通过循环添加元素来实现数组的创建。

【问题讨论】:

  • ForEach 是一个视图容器,而不是控制流操作符。
  • 好的,那么,在 SwiftUI 中还有另一种创建数组的方法吗?
  • 实际上,使用 func 可以解决问题。使用“for key in 1...5 {}”
  • 我没有意识到 ForEach 不能用作 Swift 中的 foreach。谢谢

标签: swiftui


【解决方案1】:

这是一个简单的演示

struct Test: Identifiable {
    var id:Int
    var text:String
}

struct ContentView: View {
    
    var array: [Test] = (0...3).map { Test(id: $0, text: "Testing") }
    
    var body: some View {
        VStack{
            ForEach(array) { test in
                Text("\(test.id): \(test.text)")
            }
        }
    }
}

【讨论】:

  • 您也可以在初始化程序中使用 for 循环 (for i in 0...3 in {}) 来创建数组,而不是 (0...3).map {}
猜你喜欢
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 2020-04-22
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
相关资源
最近更新 更多