Reputation: 23
I have a a covid.plist file like below and trying to figure out how to parse to the objects and read this data ?
covid.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>key1</key>
<string>value for key1</string>
<key> key2</key>
<string>valua for key1</string>
<key>Covid1</key>
<dict>
<key>covid1_key</key>
<string>covid1_value</string>
</dict>
<key>Covid2</key>
<dict>
<key>covid2_key</key>
<string>covid2_value</string>
</dict>
</dict>
</plist>
Upvotes: 2
Views: 811
Reputation: 5643
Your code seems to be infected so i wear mask, wash my hand and keep my mac little distance :) Anyway I think PropertyListDecoder
can be used to decode plist file directly to your objects for your case
struct Covid1:Codable {
var covid1_key:String?
private enum CodingKeys : String, CodingKey {
case covid2_key = "covid1_key"
}
}
struct Covid2:Codable {
var covid2_key:String?
private enum CodingKeys : String, CodingKey {
case covid2_key = "covid2_key"
}
}
struct PlistConfiguration:Codable {
var key1:String?
var covid1: Covid1?
var covid2: Covid2?
private enum CodingKeys : String, CodingKey {
case key1 = "key1"
case covid1 = "Covid1"
case covid2 = "Covid2"
}
}
And use this function for action :
func parseCovid() -> PlistConfiguration {
let url = Bundle.main.url(forResource: "covid", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let decoder = PropertyListDecoder()
return try! decoder.decode(PlistConfiguration.self, from: data)
}
Upvotes: 2