Search code examples
iosswiftswift2ios9xcode7

Swift Errors with syntax


Can someone help me fix these errors? Swift changed and I don't know how to change these to make it work with the new version:

This one gives the following error:

Cannot invoke createDirectoryAtPath with an argument list of type (SwiftCoreDataHelper.Type, withintermediateDirectories: Bool, atrributes: NilLiteralConvertible, error:inout NSError?)

NSFileManager.defaultManager().createDirectoryAtPath(SwiftCoreDataHelper, withIntermediateDirectories: true, attributes: nil, error: &error)

The next couple just give me that 'error' is an extra argument:

if storeCoordicator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error){
        if (error != nil){
            print(error!.localizedDescription)
            abort()
        }
    }

let items: NSArray = managedObjectContext.executeFetchRequest(fetchRequest, error: nil)

Solution

  • In Swift 2, you need to catch the error with do-catch block; when using addPersistentStoreWithType with CoreData, you would need to do the following:

    do
    {
        try storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    }
    catch(let error as NSError)
    {
        NSLog(error.localizedDescription) //error has occurred.
        abort() //abort
    }
    

    The same is applied for executeFetchRequest:

    do
    {
        let items: NSArray = try managedObjectContext.executeFetchRequest(fetchRequest)
    }
    catch(let error as NSError)
    {
        NSLog(error.localizedDescription)
    }
    

    As with createDirectoryAtPath:

    do
    {
        try NSFileManager.defaultManager().createDirectoryAtPath(SwiftCoreDataHelper, withIntermediateDirectories: true, attributes: nil)
    }
    catch(let error as NSError)
    {
        NSLog(error.localizedDescription)
    }