How to Read Plist without using NSDictionary in Swift?

The native Swift way is to use PropertyListSerialization

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist") {
   do {
     let data = try Data(contentsOf:url)
     let swiftDictionary = try PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
      // do something with the dictionary
   } catch {
      print(error)
   }
}


You can also use NSDictionary(contentsOf: with a type cast:

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist"),
   let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
   print(myDict)
}

but you explicitly wrote: without using NSDictionary(contentsOf…

Basically don’t use NSDictionary without casting in Swift, you are throwing away the important type information.


Meanwhile (Swift 4+) there is still more comfortable PropertyListDecoder which is able to decode Plist directly into a model.

Leave a Comment