Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

SwiftData predicate for many to many relationships?

Hello, I have a Task model in my application which has an optional many to many relationship to a User model.

task.assignedUsers

user.tasks

I am looking to construct a SwiftData predicate to fetch tasks which either have no assigned users or assigned users does not contain specific user.

Here is a partially working predicate I have now:

static func assignedToOthersPredicate() -> Predicate<Task> {
    let currentUserGUID = User.currentUserGUID
    
    return #Predicate<Task> { task in
        task.assignedUsers.flatMap { users in
            users.contains(where: { $0.guid != currentUserGUID })
        } == true
    }
}

This only returns tasks assigned to others, but not those which have no assigned users.

If combine it with this:

static func notAssignedPredicate() -> Predicate<Task> {
    return #Predicate<Task> { task in
        task.assignedUsers == nil
    }
}

Then I get a run time crash: "to-many key not allowed here"

What is the proper way to do this?

Thanks.

Yeah, this is an issue happening when testing an optional to-many relationship in a prediate. I’d suggest that you file a feedback report – If you do so, please share your report ID here for folks to track.

If your to-many relationship can be non-optional, the following code should work:

static func notAssignedPredicate() -> Predicate<Task> {
    return #Predicate<Task> { task in
        task.assignedUsers.isEmpty
    }
}

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

SwiftData predicate for many to many relationships?
 
 
Q