Search code examples
swiftswift3plist

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


I am trying to parse a plist.

The code snippet is given below:

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

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

If I set the type of myDictionary to Dictionary, I can no longer use the contentsOfFile method. Please help.


Solution

  • The (recommended) alternative is 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]