SwiftData中PredicateExpressions编译错误:类型转换失败求助
解决SwiftData谓词编译错误:无法转换PredicateExpressions类型
编译时触发如下错误:
无法将类型'PredicateExpressions.Equal<PredicateExpressions.KeyPath<PredicateExpressions.Variable, Object?>, PredicateExpressions.Value<Object?>>'转换为闭包结果类型'any StandardPredicateExpression'
问题根源
错误出在#Predicate<AttributValue>的构建代码行:SwiftData的#Predicate宏仅支持解析模型属性的直接访问、基础运算符和部分内置函数,无法识别自定义实例方法(比如你代码中的getValueAsObjectId()),导致编译时无法将闭包转换为合法的表达式树。
解决方案
直接通过AttributValue模型的属性路径构建谓词,替换自定义方法调用:
// 原错误代码 // let relationPredicate = #Predicate<AttributValue> { $0.getValueAsObjectId() == object.id } // 修改后的正确代码 let relationPredicate = #Predicate<AttributValue> { $0.relationValue?.id == object.id }
完整修改后的函数代码
static func getChildObjects(for object: Object, context: ModelContext) -> [Object] { let relationPredicate = #Predicate<AttributValue> { $0.relationValue?.id == object.id } let descriptor = FetchDescriptor<AttributValue>(predicate: relationPredicate) do { let attributValues = try context.fetch(descriptor) let objects = attributValues.compactMap { $0.attribut?.object } // Sortiere die Objekte nach Kategorie (alphabetisch) return objects.sorted { $0.category.displayName < $1.category.displayName } } catch { print("Fehler beim Abrufen der Kind-Objekte: \(error.localizedDescription)") return [] } }
补充说明
你的AttributValue模型中已经定义了relationValue(类型为Object?),直接访问其id属性即可实现与目标object.id的UUID比较,完全不需要依赖自定义方法getValueAsObjectId()。
内容的提问来源于stack exchange,提问作者Peter Bien
相关产品推荐
相关产品推荐

