Search code examples
swiftnsdictionary

I can't Unwrap a value from a plist key value


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


Solution

  • 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
    }
    // ...