Search code examples
iosarraysswiftdictionaryplist

Accessing plist array Swift XCode


I have a plist with this type of structure.

Root
  item0 Dictionary
    village string
    bars    array
        item0 dictionary
            name string
        item1 dictionary
            name string
        item2 dictionary

   item1 Dictionary
     village string
     bars   array
        item0 dictionary
            name string
        item1 dictionary
            name string
        item2 dictionary

In my code I would like to access the bars array for a specific village and then iterate over all the dictionaries in the bar array and output a string value that is in each of those dictionaries.

So far what I have to access the plist and grab the villages is this.

  var villages = [AnyObject]() 
  let filePath = Bundle.main.path(forResource: "Bars", ofType: "plist")
  if let path = filePath {
        villages = NSArray(contentsOfFile: path) as! [AnyObject]
  }

From here what would I do to access my villages array to get the bars (Array) at a specific index in that villages array?

Then from there how would I access the bars dictionary[index].string value?


Solution

  • let bars = villages[index]["bars"] as! NSArray               //get specific index bars in villiages
    let name = (bars[index] as! NSDictionary)["name"] as! String //get specific index name in bars