如何将此 .plist 文件直接解析为 Swift 中的对象?
Posted
技术标签:
【中文标题】如何将此 .plist 文件直接解析为 Swift 中的对象?【英文标题】:How can I parse this .plist file directly to the objects in Swift? 【发布时间】:2020-11-03 20:49:06 【问题描述】:我有一个如下所示的 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>
【问题讨论】:
【参考方案1】:你的代码似乎被感染了,所以我戴上口罩,洗手并保持我的 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)
【讨论】:
以上是关于如何将此 .plist 文件直接解析为 Swift 中的对象?的主要内容,如果未能解决你的问题,请参考以下文章
将 Plist (NSString) 解析为 NSDictionary
Swift:从 MainBundle 读取 plist 并直接写入 Documents 失败