是否可以从struct数组中获取一项,然后追加到SwiftUI中的其他数组?

时间:2019-11-22 22:43:25

标签: ios swift swiftui

我正在尝试从firstArray中获取金额,然后追加到secondArray。我收到此错误: “无法使用类型为'([[Number],@escaping(Double)->())'的参数列表来调用类型'ForEach <_,_,_>'的初始化程序”“

struct Number: Identifiable {
let id = UUID()
let amount: Double
}

struct ContentView: View {

@State var firstArray = [Number(amount: 10),Number(amount: 30),Number(amount: 50)]
@State var secondArray = [Double]()

var body: some View {
    VStack {
        ForEach(firstArray) { row in
            secondArray.append(row.amount)
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

任何标有@State的东西都是真理。如果第二个数组始终依赖于第一个数组,则它不应是状态变量(可以是使用map的计算属性,如下所示)。

如果确定要具有两个@State变量,则应分别对其进行初始化,而不要在视图中对其进行更改。

///MARK: - computed property
struct Number: Identifiable {
    let id = UUID()
    let amount: Double
}
struct ContentView: View {
    @State var firstArray = [Number(amount: 10),Number(amount: 30),Number(amount: 50)]
    var secondArray: [Double] = {
        return firstArray.map { $0.amount }
    }

    var body: some View {
        VStack {
//            ForEach(firstArray) { row in
//                secondArray.append(row.amount)
//            }
        }
    }
}

struct Number: Identifiable {
    let id = UUID()
    let amount: Double
}
struct ContentView: View {
    @State var firstArray = [Number(amount: 10),Number(amount: 30),Number(amount: 50)]
    var secondArray = firstArray.map { $0.amount }

    var body: some View {
        VStack {
//            ForEach(firstArray) { row in
//                secondArray.append(row.amount)
//            }
        }
    }
}

struct Number: Identifiable {
    let id = UUID()
    let amount: Double
}
struct ContentView: View {
    @State var firstArray = [Number(amount: 10),Number(amount: 30),Number(amount: 50)]
    @State var secondArray = firstArray.map { $0.amount }

    var body: some View {
        VStack {
//            ForEach(firstArray) { row in
//                secondArray.append(row.amount)
//            }
        }
    }
}

我强烈建议您使用第一个选项,因为它将始终在第二个数组中包含所有内容的amount