1

I'm trying to bind an array to a list in SwiftUI. I've been struggling to understand how to do this given that I'm quite new to SwiftUI et. al. Here's what I'm trying to:

struct ContentView: View {
    @Binding var text: String
    @Binding var results: [MKLocalSearchCompletion]

    var body: some View {
        VStack {
            MapView()
            MapSearchBar(text: $text, results: $results)
            List($results) { result in
                Text(result.title)
            }
        }
    }
}

Presently getting, Generic parameter 'SelectionValue' could not be inferred', which I understand-ish, but I can't seem to find my way...

I've not yet come across great doco on this, but I'm happy to be pointed at some.

1 Answer 1

3

results is a binding so you do not need a read-write binding in the list parameter. Also, to fix the generic parameter, add an id.

struct ContentView: View {
    @Binding var text: String
    @Binding var results: [MKLocalSearchCompletion]

    var body: some View {
        VStack {
            MapView()
            MapSearchBar(text: $text, results: $results)
            List(results, id: \.self) { result in
                Text(result.title)
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much. That did the trick. Using the $ for just for read-write now makes complete sense to me.
I like the \.self also. I've not seen that before.
I have a similar problem, but I don't understand the solution since the program looks different than in my case. I have a sample array of 3 strings called repository names inside Data class. How can I bind it to a new created list, @sfung3?

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.