【问题标题】:Alternative to the objective-NSDictionary(contentsOfFile) method in swift [duplicate]swift中objective-NSDictionary(contentsOfFile)方法的替代方法[重复]
【发布时间】:2017-11-15 07:46:13
【问题描述】:

我正在尝试解析一个 plist。

代码sn-p如下:

if let path = Bundle.main.path(forResource: Constants.plistName,    ofType: Constants.plistType) {

       guard let myDictionary = NSDictionary(contentsOfFile: path) else {
           //throw some error
       } }

如果我将 myDictionary 的类型设置为 Dictionary,我将无法再使用 contentsOfFile 方法。 请帮忙。

【问题讨论】:

    标签: swift swift3 plist


    【解决方案1】:

    (推荐的)替代方案是PropertyListSerialization

    let url = Bundle.main.url(forResource: Constants.plistName, withExtension: Constants.plistType)!
    let data = try! Data(contentsOf: url)
    let myDictionary = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
    

    【讨论】:

    • 你为什么要把它转换成键类型字符串和值类型any的字典?
    • 您之前回答过相同的问题:stackoverflow.com/a/40437034/1187415
    • 因为属性列表字典的所有键都必须是 String 并且所有支持的值类型的通用类型是 Any - @MartinR 感谢您将其标记为重复。你的记忆力比我的好;)
    猜你喜欢
    • 1970-01-01
    • 2015-01-11
    • 2021-09-12
    • 1970-01-01
    • 2017-12-04
    • 2013-02-09
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    相关资源
    最近更新 更多