2015-08-13 26 views
0

我認爲這可能是一個基本問題,但我很難在Swift中理解字典的概念。我試圖獲取基於XML的Web服務的內容,解析兩個特定的字段並將它們設置爲字符串(一個名爲「fileName」,一個名爲「fileType」),然後將這些字符串添加到字典中(讓我們調用字典「文件」)。我想不可避免地能夠在我的應用程序中稍後打印files.fileName!files.fileType!以引用給定的實例。瞭解如何將解析數據添加到字典(斯威夫特)

這裏是我一起工作的代碼;

//MARK 
func getData(theURL: String) { 

    //Define the passed string as a NSURL 
    let url = NSURL(string: theURL) 

    //Create a NSURL request to get the data from that URL 
    let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0) 

    //Begin the NSURL session 
    let session = NSURLSession.sharedSession() 

    session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in 

     let xml = SWXMLHash.parse(data!) 

     //I think this is wrong 
     var files = [String]() 

     for elem in xml["XmlResponse"]["object"] { 
      let fileName: String? = elem.element?.attributes["name"]! 
      let fileType: String? = elem.element?.attributes["type"]! 

      //I also think this is wrong 
      let file = String(fileName: fileName, fileType: fileType) 
      self.files.append(file) 

      print(self.files) 

      dispatch_async(dispatch_get_main_queue()) { 
       self.tableView.reloadData() 
      } 
     } 
    }).resume() 
} 

在前面的迭代中,我用var files = [FileData]()的FileData是我創建的用於保存的文件名和字符串的fileType一個自定義類。這是做到這一點的唯一方法嗎?我覺得我錯過了一個簡單的前提;我知道如何收集數據(並且XML解析的工作是),但我不太清楚如何將它添加到稍後可以調用的簡單字典中。

謝謝!

回答

0

你所創建具有var files = [String]()是一個數組,而不是一個字典。 爲了得到你想要的斯威夫特,你需要創建一個字典,然後使用標語法添加鍵值對:

var files = [String: String]() 
... 
files["fileName"] = fileName 
files["fileType"] = fileType 

要訪問該字典,你可以使用相同的標語法:

if let fileName = files["fileName"] { 
    ... 
} 
0

字典是從鍵到值的映射。在你的情況下,你有鑰匙fileNamefileType。並且您想要在這些鍵下存儲實際的文件名和文件類型,以便您可以使用各自的鍵訪問它們。這遠好於我所能夠的explained by Apple

下面的代碼應該做你想要什麼:

// Defining the dictionary and initializing an empty dictionary. 
var files: [String: String] = [String: String]() 

func getData(theURL: String) { 
    // snipped a lot of your code 

    //I think this is wrong 
    var files = [String]() // Yes, this is wrong! See above. 

    for elem in xml["XmlResponse"]["object"] { 
    let fileName: String? = elem.element?.attributes["name"]! 
    let fileType: String? = elem.element?.attributes["type"]! 

    // Here you store your values in the dictionary 
    files["fileName"] = fileName 
    files["fileType"] = fileType 

    print(self.files) 

    dispatch_async(dispatch_get_main_queue()) { 
     self.tableView.reloadData() 
    } 
    } 
} 

您訪問值這樣的:

let actualFileName = files["fileName"] 
let actualFileType = files["fileType"]