如何在Swift中不使用NSDictionary读取Plist? [英] How to Read Plist without using NSDictionary in Swift?

查看:848
本文介绍了如何在Swift中不使用NSDictionary读取Plist?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Swift 2中使用过这个方法

I've already used this method in Swift 2

var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}

但是不知道如何在不使用
的情况下读取Swift3中的plist NSDictionary(contentsOfFile:path)

But don't know how to read plist in Swift3 without using NSDictionary(contentsOfFile: path)

推荐答案

原生的Swift方式是使用 PropertyListSerialization

The native Swift way is to use PropertyListSerialization

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist") {
   do {
     let data = try Data(contentsOf:url)
     let swiftDictionary = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String:Any]
      // do something with the dictionary
   } catch {
      print(error)
   }
}

您还可以使用 NSDictionary(contentsOf:,使用类型转换:

You can also use NSDictionary(contentsOf: with a type cast:

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist"),
   let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
   print(myDict)
}

但你明确地写了:没有使用NSDictionary(contentsOf ...

基本上不要使用 NSDictionary 没有在Swift中进行转换,你丢弃了重要的类型信息。

Basically don't use NSDictionary without casting in Swift, you are throwing away the important type information.

这篇关于如何在Swift中不使用NSDictionary读取Plist?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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