简体   繁体   中英

Swift 2.0 migrating code Error

I'm having some troubles in code migration for Swift 1.2 to 2.0 and here's what I've been across with:

I've imported some classes written in Swift 1.2 and I've been modifying the code to Swift 2.0 as Xcode keeps warning me about some new features to change... so far so good.

Now I'm stuck with this block of code that I just can't turn around it, no matter what I do I can't fix it unfortunately and now I need your help.

The code is the following:

var storeCoordinator:NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedModel)

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

and the 2 warnings that Xcode it putting out are

  1. 'Binary operator '!=' cannot be applied to operands of type 'NSPersistentStore' and 'nil'

  2. 'Call can throw, but it is not marked with 'try' and the error is not handled

On the second one I can do a simple do{...try/catch...} method and turn it over but I'm still stuck with the first one.

Thank's for your help in advance.

PS: sorry for my bad English, hope it's understandable. cheers, Ivan.

In Swift 2.0 , addPersistentStoreWithType returns a non-optional NSPersistentStore , so you can't check against nil . If an error happens, it throws an error which you must catch:

var storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedModel)

do {
    try storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
}
catch let error as NSError {
    print(error.localizedDescription)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM