本文介绍了如何在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?
发布评论