Jake
Jake

Reputation: 13753

Misleading error with ObjectBinding and List in SwiftUI

I'm trying to setup a basic list in SwiftUI but I'm getting a compile time error that doesn't make much sense to me. Here's the error:

Cannot convert value of type 'Text' to closure result type '_'

Here is my code:

final class MainViewModel: BindableObject {
    var didChange = PassthroughSubject<MainViewModel, Never>()

    var tasks = [Task]() {
        didSet {
            didChange.send(self)
        }
    }
}

struct MainView : View {
    @ObjectBinding var mainViewModel = MainViewModel()

    var body: some View {
        List($mainViewModel.tasks) { task in
            Text(task.title!) //compile time error here
        }
    }
}

I think this is more than likely another one of SwiftUI's misleading errors, but I cannot seem to find what the actual issue is. Am I setting up the binding incorrectly? Am I missing something? Any help would be appreciated...

Upvotes: 3

Views: 2622

Answers (1)

Matteo Pacini
Matteo Pacini

Reputation: 22846

You're passing a Binding into the List.

It needs data which conforms to Identifiable.

You got two options here:

Either you make Task conform to Identifiable, or you use .identified(by:).

struct Task {
    let title: String
}

final class MainViewModel: BindableObject {
    var didChange = PassthroughSubject<MainViewModel, Never>()

    var tasks = [Task]() {
        didSet {
            didChange.send(self)
        }
    }
}

struct MainView : View {
    @ObjectBinding var mainViewModel = MainViewModel()

    var body: some View {
        // HERE
        List(mainViewModel.tasks.identified(by: \.title)) { task in
            Text(task.title) 
        }
    }
}

Upvotes: 2

Related Questions