iosswiftproperty-list

How to access a property list


I have created a property list with continents, countries, and random facts as shown below:

property list

I can access the top level keys from the property list easily enough:

if let path = NSBundle.mainBundle().pathForResource("countryData", ofType: "plist") {
            dict = NSDictionary(contentsOfFile: path)
        }
countries += dict!.allKeys as! [String]

If I wanted to access the second element in the vanuatu array, however, things fall apart. I would think objectForKey would get the country dictionary and then use objectForKey again to get the country array. But so far, that hasn't worked. At all...


Solution

  • if let path = NSBundle.mainBundle().pathForResource("countryData", ofType: "plist") {
                dict = NSDictionary(contentsOfFile: path)
    
                if let australia = dict["australia"] as? [String:AnyObject]{
                    // access the second element's property here
                if let vanuatu = australia["vanuatu"] as? [String]{
                    // Access the vanuatu here
                    } 
                }
            }