Search code examples
swiftcontainsnsset

Swift: How to check a core data NSSet for an object


I am upgrading my code to Swift and am stuck on how to replicate my objective-c code to check for an existing record in a 1:many relationship, given one of the fields

    BOOL existingRecord = [[self.employeeRecord.absences valueForKey:@"id"] containsObject:myId];

"absences" is an NSSet of "Absence" records which is part of my "Employee" record.

Clearly I could loop through "absences" and check each record like this:

if let allAbsences = self.employeeRecord.absences {
      for checkAbsence in allAbsences {
           if (checkAbsence.id == myId) {
                existingRecord = true
                break
           }
       }
}

but I lose the elegance of the objective-c solution


Solution

  • Swift also has these elegant methods. ;) Just use the same method in swift as you did in objective-c:

    var existingRecord = self.employeeRecord.absences.valueForKey("id").containsObject(myId)