1

以下に示すように、大陸、国、およびランダムな事実を含むプロパティリストを作成しました。

物件一覧

プロパティ リストからトップ レベルのキーに簡単にアクセスできます。

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

しかし、vanuatu 配列の 2 番目の要素にアクセスしたい場合は、うまくいきません。objectForKey は国の辞書を取得し、次に objectForKey を再度使用して国の配列を取得すると思います。しかし、これまでのところ、それはうまくいきませんでした。まったく...

4

3 に答える 3

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
                } 
            }
        }
于 2016-08-02T05:50:45.760 に答える
1

そのようなplistファイルからデータを取得できます。countryCodes の plist ファイルを作成しました。

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 = ""
}
于 2016-08-02T07:19:15.710 に答える