How to Read Plist without using NSDictionary in Swift?

Karthikeyan Bose

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)

vadian

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related