2014-08-28 40 views
0

果殼 - 我試圖獲得一個高分出的plist來自AnyObject的「Dynamic cast failure failure」?爲Int

這裏是讀取數據的代碼:

var myOutput: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("highscore") 
    println(myOutput!) 

這是成功的,println的結果是正確的數據

if myOutput != nil{ 
     highscore = myOutput! as Int 
    } 

這給了我一個「斯威夫特動態鑄造失敗」。從我讀過的所有東西都應該有效,所以任何提示都會很棒。

+0

可以將AnyObject更改爲int或NSInteger - 問題是否仍然存在? – Woodstock 2014-08-28 21:40:20

+0

不。我嘗試在原始var myOutput定義中添加「as Int」,但也失敗了 – 2014-08-28 21:42:26

+2

這意味着'myOutput [!]'的值不是* Int。它是什麼?一個NSString,也許? – user2864740 2014-08-28 21:44:52

回答

1

感謝用戶2864740讓我走上正軌。正確的解決方案是:

if myOutput != nil{ 
     highscore = myOutput!.integerValue 
    } 
+1

或者使用「條件賦值」:'if let theOutput = myOutput {highscore = theOutput.integerValue}' – 2014-08-28 21:56:58

+0

您可以使用'NSUserDefaults'提供的特定方法避免'String to Int'轉換:'setInteger'來保存Int和'integerForKey'來加載它。請注意''integerForKey'返回一個'Int'(而不是'Int?')。因此,如果沒有找到您作爲參數傳遞的鍵值,則返回一個Int,在這種情況下返回0。 – 2014-08-28 22:03:46

+1

@appzYourLife:但是不能區分「無值集」和「值零集」。 – 2014-08-28 22:12:56