Search code examples
iosswiftdictionaryswift3nsdictionary

How to Read Plist without using NSDictionary in Swift?


I've already used this method in Swift 2

var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}

But don't know how to read plist in Swift3 without using NSDictionary(contentsOfFile: path)


Solution

  • 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.