2016-01-20 29 views
-2

我在斯威夫特斯威夫特AnyObject作爲解釋得到了一個不存在的元素不是零

下面的代碼面臨的問題與投:

init(response: NSHTTPURLResponse, representation: AnyObject) 
{ 
    super.init(entity:NSEntityDescription.entityForName("File", inManagedObjectContext: NSManagedObjectContext.currentContext())!, insertIntoManagedObjectContext:NSManagedObjectContext.currentContext()); 

    var result : [String:AnyObject] = representation as! [String : AnyObject]; 
    if representation["result"] != nil { 
     print("result = \(representation["result"])") 
     result = representation["result"] as! [String : AnyObject] 
    } 
} 

在某些情況下,我希望代表[「結果」]等於零,在這種情況下,當我打印表示[[結果]] debuger給我爲零,但我仍然通過條件並在日誌中顯示「result = nil」,當它執行下一行時,崩潰 致命錯誤:意外地發現零,而解包一個可選值 這是正常的,因爲我試圖打開一個零值!

但我發現,如果我做的:

var result : [String:AnyObject] = representation as! [String : AnyObject]; 
if result["result"] != nil { 
    print("result = \(result["result"])") 
    result = representation["result"] as! [String : AnyObject] 
} 

它工作得很好

我知道,我知道你們當中有些人會說:你找到了解決辦法,爲什麼職位上stackoverflow- 我因爲我想了解爲什麼第一個解決方案不起作用,並且因爲我的錯誤當然不是特定於此上下文的。

回答

0

Becau如果您在檢查之前必須將representation["result"]轉換爲字典,那麼如果輸入representation["result"] as! [String : AnyObject]它應該正常工作。

1

您的代碼無法編譯,因爲representation["result"]結果

error: ambiguous use of 'subscript'

除此之外,考慮使用if let代替:

if let res = result["result"] { 
    print("result = \(res)") 
    result = res as! [String : AnyObject] 
} 

除此之外,你應該讓你蒙上安全使用guard S:

guard let result = representation as? [String : AnyObject] else { 
    // not a suitable dictionary 
    return 
} 
if let res = result["result"] { 
    guard let resultDic = res as? [String : AnyObject] else { 
     // not a suitable dictionary neither 
     return 
    } 
    print(resultDic) 
} 
+0

Thx爲答覆,我的代碼正在編譯,我不知道爲什麼它不在你身邊編譯第二,在實際中我曾經做過一個:if let result =(representation [「result」] ?? representation)如? [字符串:AnyObject]來檢查,但爲了我的解釋,我想要更一般。我正在尋找的答案是從Hussein Alzand我需要進行投擲,當我比較所以最後我做= =如果結果=((representation [「結果」]作爲?[字符串:AnyObject])??表示)作爲? [字符串:AnyObject] – Fogia

+0

對不起,但它編譯!我沒有回答你的答案,因爲侯賽因解釋說演員也必須在比較中完成。 – Fogia