swift 我们如何将自定义结构/枚举与模型和 predicate 宏一起使用?

smtd7mpg  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(124)

Swift 5.9和新的SwiftData框架引入了@Model#Predicate宏。我们现在可以在我们的模型中使用自定义枚举和结构体,如下所示:

@Model
final class Item {
    var name: Name
    var nature: Nature

    struct Name: Codable {
        let base: String
        let suffix: String?
    }

    enum Nature: Int, Codable {
        case foo = 0
        case bar = 1
        case baz = 2
    }

    init(name: Name, nature: Nature) {
        self.name = name
        self.nature = nature
    }
}

字符串
但是我们如何在Predicate中使用它们呢?所有这些例子都失败了:

// Member access without an explicit base is not allowed in this predicate (from macro 'Predicate')
let predicate = #Predicate<Item> { $0.nature == .foo }

// Cannot infer key path type from context; consider explicitly specifying a root type.
let predicate = #Predicate<Item> { $0.nature.rawValue == Item.Nature.foo.rawValue }

// No compile error, but causes the Xcode Preview to crash when used inside a @Query.
let predicate = #Predicate<Item> { $0.name.base.contains("Hello, world!") }

// Optional chaining is not supported here in this predicate. Use the flatMap(_:) function explicitly instead. (from macro 'Predicate').
let predicate = #Predicate<Item> { $0.name.suffix?.contains("Hello, world!") ?? false }

pbpqsu0x

pbpqsu0x1#

//在此 predicate 中不支持可选链接。显式使用flatMap(_:)函数。(来自宏“Predicate”)。

let predicate = #Predicate<Item> { $0.name.suffix?.contains("Hello, world!") ?? false }

-->

let predicate = #Predicate<Item> { $0.name.suffix.flatMap { $0.contains("Hello, world!") } == true }

字符串

相关问题