I have been chewing on this for a week now, and unless I am missing a very fundamental concept in Swift, this seems like a pretty serious bug.
I have a CoreData model with one-to-many relationships like so:
City -> has many Street
Also each entity has a name property of type string.
The corresponding classes are:
class City: NSManagedObject {
@NSManaged var name: String
@NSManaged var streets: NSOrderedSet
}
class Street: NSManagedObject {
@NSManaged var name: String
}
And here comes the really weird stuff:
var city:City = getCities().first!
var streets = city.streets.array as! [Street]
var streetToDelete:Street? = nil
//This works
streetToDelete = streets.first
//This is not working !!!
for street in streets {
if(street.name == "champs elysees"){
streetToDelete = street
}
}
deleteStreet(city, street:streetToDelete!)
And the deleteStreet function:
func deleteStreet(var city:City, var street:Street){
var streets = city.streets
var streetsSet:NSMutableOrderedSet = streets.mutableCopy() as! NSMutableOrderedSet
streetsSet.removeObject(street)
city.streets = streetsSet.copy() as! NSOrderedSet
saveContext()
}
So if I use streets.first, the deletion works as accepted.
But if I use the foreach loop instead nothing happens - no error is thrown, and no street is deleted. (off course I need the foreach loop to find a specific street and delete it).
How come the .first and the foreach are different?
They suppose to return me a pointer to a street in both cases.
(getCities() is a simple, straight from the book, fetch operation)
Update: After further investigation, it seems that some how the iteration itself over the streets array causes the issue.