zzzel zzzel - 1 year ago 198
Swift Question

removePersistentStore(_:) doesn't return Bool in Swift

I'm trying to store the return value of

which is clearly a
according to the documentation:


I'm using it like that:

let removed = try! storeCoordinator.removePersistentStore(store)

But get an alert that
is just

What's the deal with this? Am I missing something?

Answer Source

Return Value

YES if the store is removed, otherwise NO.

in the NSPersistentStoreCoordinator documentation refers to the Objective-C signature of the method:

- (BOOL)removePersistentStore:(NSPersistentStore *)store
                    error:(NSError * _Nullable *)error

In Swift, the method throws an error instead of returning a boolean:

func removePersistentStore(_ store: NSPersistentStore) throws

so that you can call it as

try! storeCoordinator.removePersistentStore(persistentStore)

or better:

do { 
    try storeCoordinator.removePersistentStore(persistentStore)
} catch let error as NSError {
    print("failed", error.localizedDescription)

Compare Error Handling in the "Using Swift with Cocoa and Objective-C" reference:

If the last non-block parameter of an Objective-C method is of type NSError **, Swift replaces it with the throws keyword, to indicate that the method can throw an error.
If an error producing Objective-C method returns a BOOL value to indicate the success or failure of a method call, Swift changes the return type of the function to Void.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download