如何在Swift中不使用NSDictionary读取Plist?

编程入门 行业动态 更新时间:2024-10-24 20:20:39
本文介绍了如何在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?

本文发布于:2023-07-16 07:27:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119340.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   如何在   Plist   Swift   NSDictionary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!