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?
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With