如何使用本地Swift方式来读取Swift 3中的Plist?
我已经在Swift 2中使用了这个方法
var myDict: NSDictionary? if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") { myDict = NSDictionary(contentsOfFile: path) }
但不知道如何在不使用NSDictionary(contentsOfFile:path)的情况下读取Swift3中的plist
本地Swift的方式是使用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:
types为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中投射,你正在扔掉重要的types信息。