本文介绍了如何在 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 中读取 plistNSDictionary(contentsOfFile: path)

But don't know how to read plist in Swift3 without usingNSDictionary(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, format: nil) as! [String:Any]
      // do something with the dictionary
   } catch {
      print(error)
   }
}

你也可以使用带有类型转换的 NSDictionary(contentsOf::

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

但您明确写道:不使用 NSDictionary(contentsOf...

基本上不要在没有在 Swift 中进行转换的情况下使用 NSDictionary,你会丢弃重要的类型信息.

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

与此同时(Swift 4+)还有更舒适的PropertyListDecoder,它能够将Plist 直接解码为模型.

Meanwhile (Swift 4+) there is still more comfortable PropertyListDecoder which is able to decode Plist directly into a model.

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

08-14 11:55