Reputation: 79
I'm quite new to SwiftUI and trying to pass an array in a forEach-loop to another view, but Xcode says, that my 'Property type does not match that of the 'wrappedValue' property of its wrapper type 'ObservedObject'. I also found some similar questions here, but nothing of the solutions there helped me.
When I'm using the object directly in the forEach-loop everything is working as needed. However the view I want to implement inside the loop will be quite complex, so a solution to pass it to a new struct would be great.
I would be very thankful if someone could explain to me, why this code doesn't work and what I need to do to fix it.
import SwiftUI
import Combine
struct Collectable: Identifiable, Decodable {
let id: Int
let name: String
let completion: Int
}
class AlbumViewModel: ObservableObject {
@Published var album: [Collectable] = [
.init(id: 1, name: "Album 1", completion: Int.random(in: 0...100)),
.init(id: 2, name: "Album 2", completion: Int.random(in: 0...100)),
.init(id: 3, name: "Album 3", completion: Int.random(in: 0...100)),
.init(id: 4, name: "Album 4", completion: Int.random(in: 0...100)),
]
}
struct Albums: View {
@ObservedObject var albumsVM = AlbumViewModel()
var body: some View {
VStack(spacing: 10) {
ForEach(albumsVM.album) { collectable in
AlbumCell(myAlbum: collectable)
}
}
}
}
struct AlbumCell: View {
@ObservedObject var myAlbum: Collectable /* ERROR HERE */
var body: some View {
VStack {
Text(myAlbum.name)
}
}
}
Upvotes: 3
Views: 361
Reputation: 3396
I think you want it like this:
struct AlbumCell: View {
var myAlbum: Collectable
var body: some View {
VStack {
Text(myAlbum.name)
}
}
}
Upvotes: 1