如何在Swift中将plist作为字典? [英] How do I get a plist as a Dictionary in Swift?

查看:125
本文介绍了如何在Swift中将plist作为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apple新的 Swift 编程语言并遇到一些问题...

I am playing around with Apple's new Swift programming language and have some problems...

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

Currently I'm trying to read a plist file, in Objective-C I would do the following to get the content as a NSDictionary:

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

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

How do I get a plist as a Dictionary in Swift?

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

I assume I can get the path to the plist with:

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

当这有效时(如果它是正确的? ):我如何将内容作为字典?

When this works (If it's correct?): How do I get the content as a Dictionary?

还有一个更一般的问题:

Also a more general question:

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

Is it OK to use the default NS* classes? I think so...or am I missing something? As far as I know the default framework NS* classes are still valid and alright to use?

推荐答案

你仍然可以在Swift中使用NSDictionaries:

You can still use NSDictionaries in Swift:

对于Swift 3 +

For Swift 3+

if let path = Bundle.main.path(forResource: "Config", ofType: "plist"),
   let myDict = NSDictionary(contentsOfFile: path){
    // Use your myDict here
}

旧版本的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
}

NSClasses仍然可用,并在Swift中使用完美。我认为他们可能希望尽快将焦点转移到swift,但目前swift API并不具备核心NSClasses的所有功能。

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.

这篇关于如何在Swift中将plist作为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆