WWDC セッションを見て、Swift に関する新しいプログラマー向けの本を読み、スタック オーバーフローに関する関連する質問をすべて読みました。Swift 1.2 から Swift 2.0 に移行した後、アプリのほとんどのエラーを修正しました。
ただし、まだ解決できていないことがいくつかあります。
AnyObject のダウンキャスト
エラー:
「[AnyObject]」からよりオプションのタイプ「[NSManagedObject]」にダウンキャストできません
コード:
let fetchRequest = NSFetchRequest(entityName: formulaEntity)
var error: NSError?
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]?
if let results = fetchedResults {
stocks = results
} else {
print("Could not fetch \(error), \(error!.userInfo)")
}
} catch {
print("ERROR: \(error)")
}
表示されているエラーはlet fetchedResults = try...
行で発生しています
私が抱えている別の奇妙なエラーは、AppDelegate にあります。
エラー:
「NSMutableDictionary」は「[NSObject : AnyObject]」に変換できません
コード:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Stocks.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
上記のコードに触れたことはありません。したがって、Apple の移行ツールによって、これが適切に移行されなかった理由がわかりません。
AppDelegate の別のエラー:
二項演算子 '&&' は 2 つの Bool オペランドに適用できません
Call はスローできますが、'try' とマークされておらず、エラーは処理されません。
コード:
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save() {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
繰り返しますが、AppDelegate のこの部分には触れていません。上記のコードの何が問題なのか正確にはわかりません。