[英]How can I parse this .plist file directly to the objects in Swift?
我有一個像下面這樣的 covid.plist 文件,並試圖弄清楚如何解析對象並讀取這些數據?
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>
你的代碼似乎被感染了,所以我戴上口罩,洗手並與我的 mac 保持一點距離 :) 無論如何,我認為PropertyListDecoder
可用於將 plist 文件直接解碼為你的對象的對象
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"
}
}
並使用此功能進行操作:
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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.