Loading a Swift dictionary from a plist file
/One of the things that doesn't seem to be there out of the box is serialisation support for dictionaries. This function uses NSPropertyListSerialization to achieve that returning Dictionary<String,AnyObject!>?
import Foundation func readDictionaryFromFile(filePath:String) -> Dictionary<String,AnyObject!>? { var anError : NSError? let data : NSData! = NSData.dataWithContentsOfFile(filePath, options: NSDataReadingOptions.DataReadingUncached, error: &anError) if let theError = anError{ return nil } let dict : AnyObject! = NSPropertyListSerialization.propertyListWithData(data, options: 0,format: nil, error: &anError) if dict{ if let ocDictionary = dict as? NSDictionary { var swiftDict : Dictionary<String,AnyObject!> = Dictionary<String,AnyObject!>() for key : AnyObject in ocDictionary.allKeys{ let stringKey : String = key as String if let keyValue : AnyObject = ocDictionary.valueForKey(stringKey){ swiftDict[stringKey] = keyValue } } return swiftDict } else { return nil } } else if let theError = anError { println("Sorry, couldn't read the file \(filePath.lastPathComponent):\n\t"+theError.localizedDescription) } return nil } let dictionaryFilePath = "/Users/you/your.plist" if let loadedDictionary = readDictionaryFromFile(dictionaryFilePath){ println(loadedDictionary.description) }
It's worth noting I'm not doing a deep conversion (that is the contained NSObjects are not being converted to native swift objects) because it is not clear to me that that is always desirable.