0

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

0

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]
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Why are you casting it to a Dictionary of key type string and value type any? – vasudha Jha Nov 15 '17 at 08:39
  • 1
    You answered an identical question before: https://stackoverflow.com/a/40437034/1187415. – Martin R Nov 15 '17 at 08:47
  • Because all keys of a property list dictionary are required to be `String` and the common type of all supported value types is `Any` – @MartinR Thanks for marking as duplicate. Your memory is much better than mine ;) – vadian Nov 15 '17 at 09:18