Drux Drux - 2 months ago 8
Swift Question

Asserting equality of notification object and managed object context in Swift

How can I assert that a given

NSNotification
´s
object
corresponds to a given
NSManagedObjectContext
?

This Swift expression won't compile and hence cannot do the job:

assert(notification.object! === managedObjectContext)

Answer

You can unwrap them and asset their equality by the following

guard let object = notification.object as? NSManagedObjectContext, object === moc else {
    return
}

if object === moc {
    print(object)
}

or

if let object = notification.object as? NSManagedObjectContext,
    object === moc {
    print(object)
}