替代 objective-NSDictionary(contentsOfFile) 方法 swift

Alternative to the objective-NSDictionary(contentsOfFile) method in swift

我正在尝试解析一个 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 方法。 请帮忙。

(推荐的)备选方案是 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]