skip to Main Content

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.

2

Answers


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

    ForEach(isExpanded ? items[..<items.count] : items[..<4], id: .self) { sub in
            
        }
    
    Login or Signup to reply.
  2. 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)
    }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search