Swift - read plist file to an array?

后端 未结 5 1845
忘掉有多难
忘掉有多难 2021-02-08 10:55

I have created a mini translation from English words to Spanish words. I would like to use the englishArray.plist instead of my englishArray = [\"the cat\"] How can I create thi

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 11:35

    Swift 4

    You can use Codable which is pure swift type.

    Firstly load Plist file from bundle then use PropertyListDecoder

    Complete code -

        func setData() {
            // location of plist file
            if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {
    
                do {
                    var settings: MySettings?
                    let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
                        let decoder = PropertyListDecoder()
                    settings = try decoder.decode(MySettings.self, from: data)
                    print("array  is \(settings?.englishArray ?? [""])")//prints array  is ["Good morning", "Good afternoon"]
    
    
                } catch {
                    print(error)
                }
            }
        }
    }
    struct MySettings: Codable {
    
        var englishArray: [String]?
    
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            englishArray = try values.decodeIfPresent([String].self, forKey: .englishArray)
    
        }
    }
    

提交回复
热议问题