SwiftData Predicate Issue Workaround

I actually have found a workaround to an issue I reported on earlier. Here it is by example.

let predicate = #Predicate<Data> { data in
    data.result == result
    && data.variable?.starts(with: SomeString) ?? false
}

Note the data.variable?. and the ?? false. This works. I still don't think I should have to discover these things. Something needs to be fixed on Apple's end.

Answered by SpaceMan in 761587022

By the way. The following also works.

data.variable?.contains(SomeString) ?? false

But the following items do not work even though you won't get a warning or an error.

data.variable!.starts(with: SomeString)
data.variable!.contains(SomeString)
Accepted Answer

By the way. The following also works.

data.variable?.contains(SomeString) ?? false

But the following items do not work even though you won't get a warning or an error.

data.variable!.starts(with: SomeString)
data.variable!.contains(SomeString)

You didn't provide a link to your earlier post, so I'm not sure what syntax you're fixing in this post, but if you mean that something like this doesn't compile:

data.result == result && data.variable?.starts(with: SomeString)

then that's because Swift's strong type system requires that the expressions on the left and right of && must be Bool values. An optional value, which is the result of optional chaining (….variable?.…, isn't a Bool.

If that's what we're talking about, then you could do something like this:

data.result == result && data.variable?.starts(with: SomeString) != nil

The reason why data.variable!.starts(with: SomeString) doesn't solve the problem is because it's going to abort at runtime if data.variable is nil, and that's not the behavior you want here.

It looks like the following works as well.

data.variable?.starts(with: SomeString) == true
data.variable?.contains(SomeString) == true
SwiftData Predicate Issue Workaround
 
 
Q