在Swift 2.0中我们需要从core data中query结果的时候使用的是如下方式:
func findAnimals() {
let request = NSFetchRequest(entityName:”Animal")
do {
guard let searchResults = try context.executeFetchRequest(request) as? [Animal] else {
print("Results were not of the expected structure")
}
... use(searchResults) ...
} catch {
print("Error ocurred during execution: \(error)")
}
}
注意,以上代码试图将executeFetchRequest返回的结果转换为实际数据类型的数组。同时我们看到,在建立request的时候直接使用的是NSFetchRequest的纯构造器方式。
但是在Swift 3.0中首先我们在创建request的时候必须用范型来指定实际数据类型,你可以用如下任何一句来完成: