尝试按评级 > 1 过滤图书列表并收到错误 - 闭包参数列表的上下文类型需要 1 个参数,不能隐式忽略 - 在线 List(savedFavBooks.filter({$0.rating > 1})) {
完整代码如下
import SwiftUI
import Combine
import SwiftData
struct SavedFavoriteBookView: View {
@Query private var savedFavBooks: [Book]
@Environment(\.modelContext) private var context
let skyPurple = Color(red: 161 / 255, green: 160 / 255, blue: 248 / 255)
var body: some View {
//List{
List(savedFavBooks.filter({$0.rating > 1})) {
ForEach(savedFavBooks) { book in
SavedFavBookCard(bookSavedObject: book)
.listRowBackground(Color(red: 255 / 255, green: 221 / 255, blue: 249 / 255) .opacity(0))
.navigationBarTitleDisplayMode(.inline)
}
.onDelete(perform: delete(indexSet:))
}
和图书代码
// Book.swift
import Foundation
import SwiftData
struct Result: Decodable {
let bookObjects: [Book]
}
@Model
class Book: Decodable, Identifiable, Hashable {
let id: String
let title: String
let authors: [String]
let imageURL: URL
let subjects: [String]?
let date_published: String
let synopsis : String?
var rating: Int = 0
init(id: String, title: String, subjects: [String], synopsis: String, authors: [String], date_published: String, imageURL: URL, rating: Int) {
//init(id: String, title: String, subjects: [String], authors: [String], date_published: String, imageURL: URL, rating: Int) {
self.id = id
self.title = title
self.subjects = subjects
self.authors = authors
self.date_published = date_published
self.synopsis = synopsis
self.imageURL = imageURL
self.rating = rating
}
enum CodingKeys: String, CodingKey {
case id = "isbn"
case title
case date_published
case authors
case image
case subjects
case synopsis
}
required init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
date_published = try container.decode(String.self, forKey: .date_published)
title = try container.decode(String.self, forKey: .title).trunc(length: 100)
id = try container.decode(String.self, forKey: .id)
authors = try container.decode(Array.self, forKey: .authors)
subjects = try container.decodeIfPresent(Array.self, forKey: .subjects)
synopsis = try container.decodeIfPresent(String.self, forKey: .synopsis)
imageURL = try container.decode(URL.self, forKey: .image)
} //end init
}
struct BookDataStore: Decodable {
//struct BookDataStore {
var books: [Book]
}
只需在查询中过滤书籍模型即可。