Home > Software design >  SwiftUI ForEach with array or sub-array
SwiftUI ForEach with array or sub-array

Time:06-14

I want to iterate an array using ForEach and, depending on the use-case, its sub-version with fewer elements.

 ForEach(isExpanded ? $items : $items[..<4])

The problem is if I am using a subscript, I am getting an error Result values in '? :' expression have mismatching types 'Binding<[RowItem]>' and 'Binding<[RowItem]>.SubSequence' (aka 'Slice<Binding<Array<RowItem>>>'). I can not use it like this, because it is not an array but a Slice. Just casting to Array does not work either.

CodePudding user response:

This is a sample code which responds to the poster's second question.

Use binding to store/pass/receive data from another struct:

struct Test: View {

@State var bindWithChild: String = ""

var body: some View {
    
    Text("\(bindWithChild)")
    //when you edit data in the child view, it will updates back to the parent's variable
    
    TestChild(receiveAndUpdate: $bindWithChild)
}
}

struct TestChild: View {

@Binding var receiveAndUpdate: String

var body: some View {
    TextField("Enter here", text: $receiveAndUpdate)
}
}

However, If your data only works within one struct, and you don't need to pass the data back and forth within another struct, use @State:

struct Test: View {

@State var binding: String = ""

var body: some View {
    
    Text("\(binding)")
    //when you edit data in the TextField below, it will update this Text too.
    
    TextField("Enter data: ", text: $binding)
}
}

CodePudding user response:

You don’t have to use $ sign in front of your arrays.

ForEach(isExpanded ? items[..<items.count] : items[..<4], id: \.self) { sub in
        
    }
  • Related