2014-08-30 69 views
2

鑑於字典,我需要檢查值是字典,數組或其他。 我得到以下錯誤:Swift - Case語句和MetaType檢查?

Downcast pattern value of type Dictionary cannot be used

// Type of dictionary to enumerate through 
public typealias SourceDictionary = [String: AnyObject] 
var dictionary: SourceDictionary 


for (key, value) in dictionary { 
    switch (value) { 
     case value as SourceDictionary : 
     print("Dictionary") 

     case value as Array : 
     print("Array") 

     default : 
     print("Other") 
    } 
} 

也試過

case let someValue as SourceDictionary 

回答

0

您可與一個switchif語句檢查,你的語法僅僅是不完全正確。

開關:

for (key, value) in dictionary { 
    switch value { 
    case let v as Dictionary<String, AnyObject>: 
     println("Dictionary in \(key)") 
    default: 
     println("other") 
    } 
} 

如果:

for (key, value) in dictionary { 
    if let v = value as? Dictionary<String, AnyObject> { 
     println("Dictionary in \(key)") 
    } 
} 
+0

這是特定於泛型類型?如果你看看文檔,他們有一個類似的樣本,但是用Stirng,Int等。https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html – aryaxt 2014-08-30 04:57:52

+0

對不起,以前的答案很糟糕 - 你只是缺少一些'switch'語法。 – 2014-08-30 05:06:03

+1

與switch語句的錯誤仍然存​​在 – aryaxt 2014-08-30 05:23:08