简体   繁体   English

如何在Swift中阅读Plist?

[英]How can I read Plist in Swift?

I want read a NSArray form plist , and the code : 我想读一个NSArray表单plist,代码:

func loadPlistArray() -> [Any] {

    var path: String? = Bundle.main.path(forResource:"MyCenter", ofType: "plist")

    if let arry = NSArray(contentsOfFile: path!) {
        return arry as! NSArray
    }else{
        return nil;
    }

}

but always got errors below: 但总是有以下错误:

在此输入图像描述 And After I got the data from plist, I fount that I can't see the Details of Dictionary : 在我从plist获取数据后,我发现我看不到字典的详细信息:

在此输入图像描述

And here is my plist: 这是我的plist: 在此输入图像描述

should I add a generic in the array by var plistArray : [[String:Any]]? 我应该通过var plistArray在数组中添加泛型:[[String:Any]]?

The errors messages you are getting tell you what is wrong with your method, this is how I would write the function: 您收到的错误消息告诉您方法有什么问题,这就是我编写函数的方法:

func loadPlistArray() -> [Any] { // 1
    guard
        let url = Bundle.main.url(forResource: "MyCenter", withExtension: "plist"), // 2
        let list = NSArray(contentsOf: url) as? [Any] // 3
        else { return [] } // 4

    return list
}

And some commentary: 还有一些评论:

  1. You are declaring the method to return an Array of Any items, but your method tries to return an NSArray . 您声明方法返回Any项的Array ,但您的方法尝试返回NSArray
  2. It is recommended to use the URL based methods for accessing files, rather then the string based paths. 建议使用基于URL的方法来访问文件,而不是基于字符串的路径。
  3. You have to use the Array methods to read the plist, but you can cast it to [Any] . 您必须使用Array方法来读取plist,但您可以将其强制转换为[Any] However, if you know the type of items you have in the plist, I recommend that you return a properly type array from this method eg [String] , [Int] etc. 但是,如果您知道plist中的项目类型,我建议您从此方法返回正确类型的数组,例如[String][Int]等。
  4. You don't need to return an optional if the file can't be read. 如果无法读取文件,则无需返回可选项。 Depending on how you want to handle the error you could either return an empty array (as I've shown here) or convert your function into a throwing one so that if you can't read the file an error is thrown and can be handled by the calling code. 根据您想要处理错误的方式,您可以返回一个空数组(如我在此处所示)或将您的函数转换为抛出函数,这样如果您无法读取该文件,则会抛出错误并可以处理通过调用代码。

Your method signature clearly states that it returns an [Any] (ie, Swift native Array containing elements of any type whatsoever), while you try to cast the return value into NSArray (even though it already is by virtue of intialization: NSArray(contentsOfFile:) ). 您的方法签名清楚地表明它返回一个[Any] (即包含任何类型元素的Swift本机Array ),同时您尝试将返回值NSArray转换为NSArray (即使它已经由于初始化: NSArray(contentsOfFile:) )。

Change it to: 将其更改为:

return arry as? [Any] 
// (will return nil if the cast fails - not a problem if you
//  also apply the fix mentioned below...)

The other path tries to return nil ; 另一条路径试图返回nil ; for that to be acceptable, your signature needs to be defined as returning an optional : 为了使其可接受,您的签名需要定义为返回可选

func loadPlistArray() -> [Any]  // WRONG

func loadPlistArray() -> [Any]? // RIGHT

EDIT: If your app is structured in such a way that you can't afford to return nil from your method, you can instead return an empty array on failure: 编辑:如果你的应用程序的结构是这样的,你不能从你的方法返回nil ,你可以在失败时返回一个空数组:

else {
    return [] // Empty array
}

(use [:] for empty dictionary) (使用[:]作为空字典)


Also, try to avoid using ! 另外,尽量避免使用! whenever possible, and switch to ? 只要有可能,切换到? instead, unless you are 100% sure that whatever it is you are forcing will not fail and cause a runtime error (crash). 相反,除非你100%确定无论你强迫什么都不会失败并导致运行时错误(崩溃)。

I am using something like this in my project. 我在我的项目中使用这样的东西。

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

I have another plist for color which have array as a root. 我有另一个颜色的plist,它有一个数组作为根。

        if let fileUrl = Bundle.main.url(forResource: "color", withExtension: "plist"),
        let data = try? Data(contentsOf: fileUrl) {
        if let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [Any] {
            print(result)
        }
    }
     return (arry ) as! [Any]

您不能在Any类型上返回NSArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM