How can I read a property list from data in Swift

2019-01-28 07:22发布

I'm trying to read a property list from Data in Swift 3 but I can't achieve that.

I'm tried something like this:

let datasourceDictionary = try! PropertyListSerialization.propertyList(from: data!, options: [PropertyListSerialization.ReadOptions], format: nil) as! Dictionary

and a I got this error:

Cannot convert value of type 'PropertyListSerialization.ReadOptions.Type' (aka 'PropertyListSerialization.MutabilityOptions.Type') to expected element type 'PropertyListSerialization.MutabilityOptions'

Then I tried something like this like I used to do on Swift 1.2:

let datasourceDictionary = try! PropertyListSerialization.propertyList(from: data!, options: [PropertyListSerialization.MutabilityOptions.immutable], format: nil) as! Dictionary

And I got this error:

'immutable' is unavailable: use [] to construct an empty option set

Then I tried this:

let datasourceDictionary = try! PropertyListSerialization.propertyList(from: data!, options: [], format: nil) as! Dictionary

and I got this error:

'[Any]' is not convertible to 'PropertyListSerialization.ReadOptions' (aka 'PropertyListSerialization.MutabilityOptions')

How can I read the property list file from `Data in Swift 3 or what is the way to do that?

3条回答
爷的心禁止访问
2楼-- · 2019-01-28 07:57

The documentation says that the .propertyList(from:...) function returns "a property list object". It also says that "property list objects include NSData, NSString, NSArray, NSDictionary, NSDate, and NSNumber objects". Your third attempt is therefore the closest; you only need to cast the return value to NSDictionary:

let datasourceDictionary = try! PropertyListSerialization.propertyList(from: data!, options: [], format: nil) as! NSDictionary

The accepted answer of casting it to [String: Any] certainly works too, but in case someone stumbles upon this question with a property list where the root object is an array (like myself) then it's good to know that the result should be cast into NS_something, like NSArray or NSDictionary.

查看更多
ら.Afraid
3楼-- · 2019-01-28 08:13

Dictionary is a generic type which needs type information for the keys and the values.

Use Dictionary<String,Any> or shorter [String:Any]:

let datasourceDictionary = try! PropertyListSerialization.propertyList(from:data!, format: nil) as! [String:Any]

The options parameter can be omitted.

查看更多
Explosion°爆炸
4楼-- · 2019-01-28 08:20
  1. In Swift use [String:Any] usually. and value add "nil" type.
  2. You should set options "[]"

    let pathStr = Bundle.main.path(forResource: "Info", ofType: "plist")
    let data :NSData? = NSData(contentsOfFile: pathStr!)
    let datasourceDictionary = try! PropertyListSerialization.propertyList(from: data as! Data, options: [], format: nil) as! [String:Any]
    print(datasourceDictionary.self)
    

enter image description here

查看更多
登录 后发表回答