快速阅读

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (19)

正在尝试读取一个plist文件,在Object-C中,我将执行以下操作以获得NSDicary的内容:

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

我想我可以通过以下方法找到通往plist的路径:

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

如果这是正确的,我如何获得作为字典的内容?

提问于
用户回答回答于

可以在SWIFT中使用NSDictionary:

代表SWIFT 3+

var myDict: NSDictionary?
if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {
    myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
    // Use your dict 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
}

NSClass仍然可以在SWIFT中使用。目前,快速API并不具备核心NSClass的全部功能。

用户回答回答于

如果我想将.plist转换为SWIFT字典,我就是这样做的:

if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
  if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {
    // use swift dictionary as normal
  }
}

为SWIFT 2.0编辑:

if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
    // 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] {
        // use swift dictionary as normal
}

扫码关注云+社区