2017-02-09 82 views
0

我試圖解析類型的詞典[字符串:任何],我這字典中無法解析的字典爲我所期望的:字典詞典雨燕

var monsterDictionary = Dictionary<String, Any>() 

monsterDictionary["stringTest"] = "I'm a string" 
monsterDictionary["numberTest"] = "12345" 
monsterDictionary["arrayTest"] = [1,3,4,"five"] 
monsterDictionary["dictTest"] = ["key for number": 123.2 , "key for string" : "hello"] 
monsterDictionary["foo-values"] = ["foo-type": foo.FooValueType.fooValuePercent, "foo-value": 25] 


for fooItem in (monsterDictionary["foo-values"] as! [String: Any]) 
{ 
    let fooType = fooItem["tip-type"] 

最後分配產生以下錯誤:「類型」(鍵:字符串,值:任何)沒有下標成員。「

+0

你的數據結構很奇怪。它會始終包含這些完全相同的密鑰? – Alexander

+0

不,它用於測試不同的字典條目類型。只有「foo-values」會導致我遇到任何問題。 – jglasse

回答

2

Dictionary進行迭代得到鍵/值元組。

如果你確實需要遍歷所有的鍵/值,那麼你可以這樣做是這樣的:

for (key, value) in (monsterDictionary["foo-values"] as! [String: Any]) { 
    print(key, value) 
} 

如果你只是希望獲得價值tip-type,那麼你可以這樣做這個:

let fooValues = (monsterDictionary["foo-values"] as! [String: Any]) 
let fooType = ["tip-type"] as! foo.FooValueType 
+0

如果你沒有指定密鑰,它只會產生元組,我想。 爲fooItem在(monsterDictionary [ 「FOO值」]應產生: [ 「富型」:foo.FooValueType.fooValuePercent, 「富值」:25] ,而不是屈服 (「foo-值「,[」foo-type「:foo.FooValueType.fooValuePercent,」foo-value「:25]) 我錯了嗎? – jglasse

+0

下標產生'[」foo-type「:foo.FooValueType.fooValuePercent,」foo ,然後你在for循環中遍歷結果,得到'(「foo-type」,foo.FooValueType.fooValuePercent)'和'(「foo-value」,25)''元組 – Alexander

+0

我被目標C等價物弄糊塗了,我正在翻譯: for(NSDictionary * foo in [MonsterDictionary objectForKey:@「foo-values」]){ Foo * fooObject = [[Foo alloc] initWithFooType:(FooValueType)[[foo objectForKey:@「tip-type」] integerValue] Value:[foo objectForKey:@「foo-value」]]; – jglasse