How do I get a plist as a Dictionary in Swift?
You can still use NSDictionaries in Swift:
For Swift 4
var nsDictionary: NSDictionary? if let path = Bundle.main.path(forResource: "Config", ofType: "plist") { nsDictionary = NSDictionary(contentsOfFile: path) }
For Swift 3+
if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let myDict = NSDictionary(contentsOfFile: path){ // Use your myDict here}
And older versions of Swift
var myDict: NSDictionary?if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") { myDict = NSDictionary(contentsOfFile: path)}if let dict = myDict { // Use your dict here}
The NSClasses are still available and perfectly fine to use in Swift. I think they'll probably want to shift focus to swift soon, but currently the swift APIs don't have all the functionality of the core NSClasses.
This is what I do if I want to convert a .plist to a Swift dictionary:
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") { if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> { // use swift dictionary as normal }}
Edited for Swift 2.0:
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] { // use swift dictionary as normal}
Edited for Swift 3.0:
if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] { // use swift dictionary as normal}
In swift 3.0 Reading from Plist.
func readPropertyList() { var propertyListFormat = PropertyListSerialization.PropertyListFormat.xml //Format of the Property List. var plistData: [String: AnyObject] = [:] //Our data let plistPath: String? = Bundle.main.path(forResource: "data", ofType: "plist")! //the path of the data let plistXML = FileManager.default.contents(atPath: plistPath!)! do {//convert the data to a dictionary and handle errors. plistData = try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as! [String:AnyObject] } catch { print("Error reading plist: \(error), format: \(propertyListFormat)") } }