Как получить доступ к списку свойств

Я создал список свойств с континентами, странами и случайными фактами, как показано ниже:

список свойств

Я могу получить доступ к ключам верхнего уровня из списка свойств достаточно легко:

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

Однако, если бы я хотел получить доступ ко второму элементу в массиве vanuatu, все развалилось. Я бы подумал, что objectForKey получит словарь страны, а затем снова использует objectForKey, чтобы получить массив страны. Но до сих пор это не сработало. Совсем...

3 ответа

Решение
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
                } 
            }
        }
if let path = NSBundle.mainBundle().pathForResource("Property List", ofType: "plist") {
       dict = NSDictionary(contentsOfFile: path)
        if let vanuatu = dict.objectForKey("australia") as? [String:AnyObject]{
            if let vanuatuArray = vanuatu["vanuatu"] as? [String]{
                print(vanuatuArray[1])
            }
        }

    }

Вы можете получить данные из файла plist. Я создал файл plist для countryCodes.

func fetchCounrtyCodes() -> [CountryCodes]{
let name = "name"
let dial_code = "dial_code"
let code = "code"

var countryArray = [CountryCodes]()

guard let filePath = NSBundle.mainBundle().pathForResource("CountryList", ofType: "json") else {
    print("File doesnot exist")
    return []
}
guard let jsonData = NSData(contentsOfFile: filePath) else  {
    print("error parsing data from file")
    return []
}
do {
    guard let jsonArray = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? [[String:String]] else {
        print("json doesnot confirm to expected format")
        return []
    }
    countryArray = jsonArray.map({ (object) -> CountryCodes in
        return CountryCodes(name: object[name]!, dial_code:object[dial_code]!, code: object[code]!)
    })
}
catch {
    print("error\(error)")
}
return countryArray
}

struct CountryCodes{
var name = ""
var dial_code = ""
var code = ""
}
Другие вопросы по тегам