如何在Swift中将plist作为字典?

我在玩苹果的新Swift编程语言,遇到了一些问题...


当前,我正在尝试读取plist文件,在Objective-C中,我将执行以下操作以将内容作为NSDictionary获取:


NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];

NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];

如何在Swift中将plist作为字典?


我假设我可以通过以下方式获得plist的路径:


let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")

当这可行时(如果正确的话?):如何将内容作为字典?


还有一个更笼统的问题:


是否可以使用默认的NS *类?我想是...还是我错过了什么?据我所知,默认框架NS *类仍然有效并且可以使用吗?


慕哥9229398
浏览 803回答 3
3回答

慕仙森

在Swift 3.0中,从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)")        }    }

MMMHUHU

您仍然可以在Swift中使用NSDictionaries:对于Swift 4 var nsDictionary: NSDictionary? if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {    nsDictionary = NSDictionary(contentsOfFile: path) }对于Swift 3+if let path = Bundle.main.path(forResource: "Config", ofType: "plist"),   let myDict = NSDictionary(contentsOfFile: path){    // Use your myDict here}和旧版的Swiftvar myDict: NSDictionary?if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {    myDict = NSDictionary(contentsOfFile: path)}if let dict = myDict {    // Use your dict here}NSClasses仍然可用,并且可以在Swift中完美使用。我认为他们可能希望很快将重点转移到swift,但是目前swift API并没有核心NSClasses的所有功能。

30秒到达战场

如果我要将.plist转换为Swift字典,这就是我要做的事情:if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {&nbsp; if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {&nbsp; &nbsp; // use swift dictionary as normal&nbsp; }}为Swift 2.0编辑:if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {&nbsp; &nbsp; // use swift dictionary as normal}为Swift 3.0编辑:if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {&nbsp; &nbsp; &nbsp; &nbsp; // use swift dictionary as normal}
打开App,查看更多内容
随时随地看视频慕课网APP