替代swift中的objective-NSDictionary(contentsOfFile)方法

时间:2017-11-15 07:46:13

标签: swift swift3 plist

我正在尝试解析一个plist。

下面给出了代码段:

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方法了。 请帮忙。

1 个答案:

答案 0 :(得分:0)

(推荐)替代方案为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]