Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with ForEach in SwiftUI

Tags:

swiftui

I'm trying to create a list from an array of Request objects.

I have defined a custom view RequestRow to display a Request.

The following works to display a list of requests…

struct RequestsView : View {

    let requests: [Request]

    var body: some View {
        List {
            ForEach(0..<requests.count) { i in
                RequestRow(request: self.requests[i])
            }
        }
    }
}

but the following won't compile…

struct RequestsView : View {

    let requests: [Request]

    var body: some View {
        List {
            ForEach(requests) { request in
                RequestRow(request: request)
            }
        }
    }
}

Cannot convert value of type '(Request) -> RequestRow' to expected argument type '(_) -> _'

Any thoughts as to what the issue might be?

like image 854
Ashley Mills Avatar asked Jun 09 '19 15:06

Ashley Mills


2 Answers

OK, I soon figured out the answer. Per the Apple's docs, the array elements must be Identifiable, so this works…

var body: some View {
    List {
        ForEach(requests.identified(by: \.self)) { request in
            RequestRow(request: request)
        }
    }
}

I'm sure I won't be the last person to have this problem, so I'll leave this here for future reference.

like image 144
Ashley Mills Avatar answered Oct 17 '22 23:10

Ashley Mills


I have the same problem, but in my case Component is a Protocol, so it can't be conformed to Identifiable

VStack {

       ForEach(components.identified(by: \.uuid)) { value -> UIFactory in
            UIFactory(component: value)
       }
}

However, If I try something like this it works fine

VStack {

       ForEach(components.identified(by: \.uuid)) { value -> UIFactory in
            Text(value.uuid)
       }
}
like image 34
Sorin Lica Avatar answered Oct 17 '22 22:10

Sorin Lica