ios 如何在SwiftData和SwiftUI中使用SwiftMacros从数组中过滤对象

23c0lvtd  于 2023-06-25  发布在  iOS
关注(0)|答案(2)|浏览(129)

我计划在Xcode 15 Beta中使用iOS 17 Beta创建一个迷你项目。
使用SwiftData和SwiftUI创建新项目

import SwiftUI
    import SwiftData
    
    struct HomeScreen: View {
        
        @Environment(\.modelContext) private var modelContext
        @Query private var dayLogs: [DayLog]
                
        var todayLog: DayLog {
            #Predicate({}) var DayLog // how to predicate currentDay record from dayLogs.

        }
       ...

日日志SwiftModel为

@Model
    final class DayLog: Identifiable {
        let id = UUID()
        
        var createdDate: Date
        
        var note: String = ""

    }

我不知道如何使用Swift Macros #Predicate过滤这个数组

rqcrx0a6

rqcrx0a61#

由于您正在为dayLogs使用@Query,因此已经获取了值。
如果你想用一些 predicate 来获取值,最好使用

@Query(filter: Predicate, sort: KeyPath, order: SortOrder, animation: Animation)

或者:

@Query(<descriptor: FetchDescriptor>, animation: Animation)

如果要在获取数据后进行筛选,请使用简单的.filter()

q8l4jmvw

q8l4jmvw2#

我试过这个逻辑。我觉得挺好的。

extension Collection where Element == DayLog {

    /// Today Log filter.
    func todayLog() -> [DayLog] {
        let currentDate = Date()

        let from = currentDate.startOfDay
        let to = currentDate.endOfDay

        let todayPredicate = #Predicate<DayLog> { from < $0.startDate && $0.startDate < to }

        do {
            let result = try filter(todayPredicate)
            return result

        } catch let error {
            print("Failed to filter today record from DayLog. Error: \(error.localizedDescription)")
        }
        return []
    }
}

对于Date函数:

extension Date {

    var startOfDay: Date {
        return Calendar.current.startOfDay(for: self)
    }

    var endOfDay: Date {
        var components = DateComponents()
        components.day = 1
        components.second = -1
        return Calendar.current.date(byAdding: components, to: startOfDay)!
    }
}

调用方式:

let todayLog = self.dayLogs.todayLog().last

相关问题