Search code examples
iosswiftswiftdata

Swift #Predicate Macro condition


I am not able to use #Predicate Macro for simple condition.

for point in pendingList {
    do {
        let predicate: Predicate<ElevationPendingList> = #Predicate {
            $0.lat == point.lat //It throws error, I will attach error at bottom.
        }
            
        // Create a FetchDescriptor with the predicate
        let descriptor = FetchDescriptor<Item>(predicate: predicate)
        if let matchedPoint = try modelContext?.fetch(descriptor).first {
            modelContext?.delete(matchedPoint)
        }
    } catch {
        print("Error saving model object:", error)
    }
}

ERROR:-

Cannot convert value of type 'PredicateExpressions.Equal<PredicateExpressions.KeyPath<PredicateExpressions.Variable<ElevationPendingList>, Double>, PredicateExpressions.KeyPath<PredicateExpressions.Value<ElevationDataModel>, Double>>' to closure result type 'any StandardPredicateExpression<Bool>'

Solution

  • You can't access a property on an object, point.lat, inside a predicate you need to do it outside

    let latitude = point.lat
    let predicate: Predicate<ElevationPendingList> = #Predicate {
        $0.lat == latitude
    }