我试图将我的Swift 1代码转换为Swift 2.1.1代码。 所以我想添加一个fetchRequest。
在Swift 1中我这样做了:
if let results = context.executeFetchRequest(fetchRequest, error:&error),
let managedObject = results.first as? NSManagedObject {
context.deleteObject(managedObject)
}
let saveError: NSError?
context.save(nil)
和
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]?
if let results = fetchedResults {
people = results
}
else {
print("Could not fetch \(error), \(error!.userInfo)")
}
Swift 2.1(第二次请求 - >不起作用):
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
// success if it gets here
if let results = fetchedResults {
people = results
}
} catch let error as NSError {
// failed so print error
print("Error: \(error.localizedDescription)")
}
行中的错误(if let results... & let fetchedResults...
):
Initializer for conditional binding must have Optional type, not '[AnyObject]'
Call can throw, but is not marked with 'try' and the error is not handled
行中的错误(let fetchedResults...
):
Call can throw, but is not marked with 'try' and the error is not handled
Cannot downcast from '[AnyObject]' to a more optional type '[NSManagedObject]?'
你能帮我把它翻译成Swift 2.1.1吗? 谢谢你的帮助!
答案 0 :(得分:1)
您可以将其打包在do
catch
块中。如果let results
行失败,它将打印错误。
do {
let results = try context.executeFetchRequest(fetchRequest)
// success if it gets here
if let managedObject = results.first as? NSManagedObject {
context.deleteObject(managedObject)
}
} catch let error as NSError {
// failed so print error
print("Error: \(error.localizedDescription)")
}
修改强>
第二次请求:
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)
// success if it gets here
if let results = fetchedResults as? [NSManagedObject]{
people = results
}
} catch let error as NSError {
// failed so print error
print("Error: \(error.localizedDescription)")
}