Reputation: 3293
I'm new to swift and I'm trying to load a property from a nsDictionary to vTitle
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
let vTitle:String = nsDictionary["LbVacationsTitle"]
When I debug I see the right keys in nsDictionary but I can't unwrap the value of just one key The type of LbVacationsTitle is a string
Upvotes: 1
Views: 75
Reputation: 285190
Please don't use the NSDictionary
API in Swift to read a property list.
There is PropertyListSerialization
(or even PropertyListDecoder
)
let url = Bundle.main.url(forResource: "AppData", withExtension: "plist")!
let data = try! Data(contentsOf: url)
let dictionary = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
let vTitle = dictionary["LbVacationsTitle"] as! String
As the file is immutable in the application bundle any crash reveals a design mistake
Upvotes: 1
Reputation: 31016
Depending on your style preference...
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
if let dict = nsDictionary {
let vTitle = dict["LbVacationsTitle"] as? String
if let vt = vTitle {
// ...
}
}
...or...
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "AppData", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
guard let dict = nsDictionary else {
print("Couldn't get a valid dictionary")
return
}
let vTitle = dict["LbVacationsTitle"] as? String
guard let vt = vTitle else {
print("Couldn't find a string matching LbVacationsTitle")
return
}
// ...
Upvotes: 1