Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Syntax to Loop Through Core Data NSSet

Whenever I loop through my core data relations (NSSet) I have to either convert the set to an array:

for student in classroom.students.allObjects as! [Student] {
    print(student.name)
}

Or I can loop through the set normally but I have to typecast the item before I can use it:

for student in classroom.students {
    let s = student as! Student
    print(s.name)
}

I know this is trivial but all I want to do is simply pre-specify the cast for NSSet in the loop without having to do these work arounds?

When I try to do this:

for student: Student in classroom.students {
    print(student.name)
}

I get an error: Expression type 'NSSet' is ambiguous without more context

if I try something like this:

for student in classroom.students as! NSSet([Student]) {
    print(student.name)
}

I get an error: Braced block of statements is an unused closure

Is there a proper way to loop through an NSSet from Core Data and have the type pre-defined?

like image 901
Travis M. Avatar asked Nov 06 '15 21:11

Travis M.


1 Answers

Assuming that the students relationship is a to-many relationship to Student, you can cast the relationship to a Swift set using generic-style syntax:

for student in classroom.students! as! Set<Student> {
    print(student.name)
}
like image 158
Tom Harrington Avatar answered Oct 24 '22 16:10

Tom Harrington