我在Swift中創建了一個循環動態字典的函數,但是當我嘗試檢查值是否爲字典型時,類型比較條件總是失敗,實際上XCode引發了以下警告作爲提示:如何檢查值類型是否字典<String, Any>
Cast from '(key: String, value: Any)' to unrelated type 'Dictionary<String, Any>' always fails.
我不想轉換任何值,我只是想檢查變量值是否有類型字典。
這是我的代碼:
func readNode(node: Dictionary<String, Any>, level: Int)
{
// Print spaces
for _ in 0 ... level
{
print(" ")
}
for (key, val) in node.enumerated()
{
// The following condition is always false (here is the issue)
if val is Dictionary<String, Any> {
print("Key \(key):")
readNode(node: val, level: (level + 1) * 2)
}
else
{
print("Key \(key): \(val)")
}
}
}
var mydict = Dictionary<String, Any>()
mydict = ["subindex2": 2, "subindex3": 3, "subindex4": ["whatever": "extra"]]
readNode(node: mydict, level: 0)
我使用斯威夫特3.0.1。
你爲什麼在'node'參數上使用枚舉? –