我遇到了一些我无法弄清楚的语法问题。我没有强大的Swift背景,所以答案很容易(我希望。)所以,这里是片段:
public func getLatestDate()-> NSDate? {
var request = NSFetchRequest()
var entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext)
request.entity = entity
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
request.sortDescriptors = sortDescriptors
var error: NSError? = nil
do {
let results = try self.managedObjectContext.executeFetchRequest(request)
} catch {
fatalError("Failed to fetch employees: \(error)")
}
var date: NSDate?
if results != nil {
let managedObject: NSManagedObject = results![0] as NSManagedObject
date = managedObject.valueForKey("timeStamp") as? NSDate
}
return date
}
问题在于if results != nil
和以下行中的results
会引发错误说明:
使用未解析的标识符'结果'
如何解决此问题?
谢谢。
-Matt
答案 0 :(得分:1)
您在此处声明results
:
do {
let results = try self.managedObjectContext.executeFetchRequest(request)
} catch {
fatalError("Failed to fetch employees: \(error)")
}
所以你可以看到它是在do-catch
区块内完成的。这意味着您尝试使用它的位置超出了定义的范围,因此它根本无法看到它。当你到达if results != nil
时,它已经超出范围并且已经消失。
答案 1 :(得分:0)
除了Gavin之外:这可能是因为Gavin提到的原因
do {
let results = try self.managedObjectContext.executeFetchRequest(request)
if results != nil {
let managedObject: NSManagedObject = results![0] as NSManagedObject
date = managedObject.valueForKey("timeStamp") as? NSDate
}
} catch {
fatalError("Failed to fetch employees: \(error)")
}