swift - 如何在 Swift 中从另一个结构编辑一个结构中的数组?

标签 swift struct scope swiftui inout

我在名为 WorkoutBuilderView 的结构中有一组“锻炼集”。我的问题是我需要从嵌套在 WorkoutBuilderView 中的结构访问该数组的内容(如下所示)。此结构不需要嵌套在 WorkoutBuilderView 中,但它是首选。我唯一真正需要的是能够从另一个结构编辑 sets 数组。

可能为结构创建一个“inout”类型的参数? (据我所知,这仅适用于方法)

  • 需要访问的数组称为集合
  • 需要访问的位置用注释标出//access point

代码:

struct WorkoutBuilderView: View {


@State var sets = [WorkoutSet(id: 0, percentage: -1, repetitions: -1, alteredValue: .max)]

var body: some View {
    Background {
        Group {
            ...
            if self.sets.count > 0 {
                ScrollView {
                    ForEach(self.sets) { set in
                        WorkoutSetLayout(index: set.id) //where sets needs to be passed in
                    }
                }

            }
            ...
        }
    }
    }

//this is the struct where the array needs to be accessed
struct BuilderPicker: View {

    let name: String
    let options: Array<String>
    let setIndex: Int


    @State var selectedOption = 0
    var body: some View {
        HStack {
            ...
        }

        .onReceive([self.selectedOption].publisher.first()) { (value) in

            //change sets here
            //access point
            print(value)

        }
    }

}

//layout (sets needs to pass through here too)
struct WorkoutSetLayout: View {
    let index: Int
    var body: some View {
        VStack(alignment: .leading) {
            Text("Set \(index + 1)")
            ...
            //the array needs to go into the BuilderPicker where it will be edited
            BuilderPicker(name: "Weight % of", options: [AlteredValue.max.rawValue, AlteredValue.weight.rawValue], setIndex: index)
            ...
        }
    }
}
//you probably don't need to worry about the Background
struct Background<Content: View>: View {
    private var content: Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content()
    }

    var body: some View {
        EmptyView()
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
            .overlay(content)
            .padding(.top, 75)
    }
}


}

最佳答案

如果我正确理解你的问题,@Binding 就是为了这个目的

1) 将绑定(bind)变量添加到嵌套结构中,如

//layout (sets needs to pass through here too)
struct WorkoutSetLayout: View {
    let index: Int
    @Binding var data: [WorkoutSet]
    ...

2) 通过初始化器嵌套在父级中绑定(bind)模型,如

ForEach(self.sets) { set in
    WorkoutSetLayout(index: set.id, data: self.$sets)
}

关于swift - 如何在 Swift 中从另一个结构编辑一个结构中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58686591/

相关文章:

c++ - 在数组声明中使用常量结构成员

java - 在java中使用超出范围的变量

swift - 在 swift 的通知 block 中引用自己

ios - ScaleAspectFit 空格,imageView.image nul

c++ - 同名结构,不同定义 : segmentation fault with -O2

c - 返回一个指针,该指针是本地声明的 wchar_t

c# - 委托(delegate)和变量作用域

ios - 遵守 iOS 13 应用更新截止日期需要哪些更改

xcode - AppleTV + Swift + MP4 + Xcode?如何在 xcodeproj 中显示 .mp4?

ios - 在 C 中分配/释放结构指针的动态数组