hungrxyz
hungrxyz

Reputation: 854

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

I'm trying to store the return value of removePersistentStore(_:) which is clearly a Bool according to the documentation:

Doc

I'm using it like that:

let removed = try! storeCoordinator.removePersistentStore(store)

But get an alert that removed is just Void: Alert

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

Upvotes: 0

Views: 153

Answers (1)

Martin R
Martin R

Reputation: 539975

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.

Upvotes: 2

Related Questions