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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With