0

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 2

1

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)
}
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

4 Comments

That is not really my problem
check my new solution which I just edit. It worked.
How would you use binding in this case? I am new to SwiftUI
check my other answer within this post. I posted you a sample.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.