2015-01-12 25 views
1

我有被設置爲以下所示的的plist:在具有多維陣列的字典的plist夫特環

enter image description here

我想在每個的該加載到一個變量,然後循環項目。這是我到目前爲止的代碼,但無濟於事我看到錯誤「Type'AnyObject'不符合協議'SequenceType'」。

func startTournament(sender: UIBarButtonItem) { 
    var map: NSDictionary? 
    if let path = NSBundle.mainBundle().pathForResource("knockout_single_8", ofType: "plist") { 
     map = NSDictionary(contentsOfFile: path) 
    } 

    var matches = NSMutableDictionary() 
    let rounds = map?["rounds"] as NSArray 
    for match in rounds[0] { // Error from this line 
     let mid = match["mid"] 
     let match = ["names": ["testA", "testB"]] 
     matches[mid] = match 
    } 
} 
+0

您可以發佈引發'Type'AnyObject'的行不符合協議'SequenceType'。但是,我認爲輪是一個可選類型的變量,嘗試'讓rounds = map![「rounds」]作爲NSArray' – gabuh

+0

@ gabuh謝謝,我已經添加了一段代碼註釋,以顯示哪條線吐出了錯誤。我嘗試了你的建議,但同樣的錯誤在那裏。 – Fenda

+0

在for之前加上'var rounds0:Array = rounds [0] as Array',並迭代rounds0,不輪迴[0] – gabuh

回答

3

您所遇到的問題是,基礎類交易在AnyObject S,但對於這樣想for循環,即不工作:

import Foundation 
let o: AnyObject = [1,2,3] 

// this won't work, even though o _is_ an array 
// error: type 'AnyObject' does not conform to protocol 'SequenceType' 
for i in o { 

} 

// this is perhaps surprising given this does: 
o[0] // returns 1 as an AnyObject! (that's a syntactic ! not a surprise/shock ! :) 

您可能會發現更容易較早轉換爲Swift類型,然後直接使用它們。這樣做的缺點是,如果你在你的plist中存儲異構數據(即一個既有字符串又有整數的數組)。但它不看你做什麼,所以你可以寫你這樣的代碼:

func startTournament() { 
    if let path = NSBundle.mainBundle().pathForResource("proplist", ofType: "plist") { 
     if let map = NSDictionary(contentsOfFile: path) { 

      var matches: [Int:[String:[String]]] = [:] 

      if let rounds = map["rounds"] as? [[[String:Int]]] { 

       for match in rounds[0] { 
        if let mid = match["mid"] { 
         let match = ["names": ["testA", "testB"]] 
         matches[mid] = match 
        } 
       } 
      } 

     } 
    } 
} 

就個人而言,我覺得這是很容易一眼就明白,因爲你是在處理每一級的類型更容易看到並理解,你不會混淆as?is等。這樣做的一個很大的缺點是,如果你想在同一個集合中處理多個不同的類型。然後,您需要將AnyObject更長一些,並在內部循環中執行更細粒度的as?

一旦你有了上述的要求,你可以做的更多的技巧來更好地處理選項,並避免很多可怕的問題,用地圖和過濾器等代替循環,但是最好先適應這個版本。此外,此代碼缺少可處理和報告失敗案例的各種else子句。

+0

非常感謝您花時間解釋。這幫了我很多! – Fenda

+0

Swift 3有沒有更新? – Pavlos