Search code examples
swiftdictionaryoptional-chaining

How to use optional chaining while searching through a dictionary in swift?


I want to safely search through values in a swift Dictionary using if lets and making sure it is type safe as I get deeper and deeper into the dictionary. The dictionary contains dictionaries that contains NSArray that contains more dictionary.

At first attempt my code looks like this:

  if let kkbox = ticket["KKBOX"] as? Dictionary<String, AnyObject> {
        if let kkboxDlUrlDict = kkbox["kkbox_dl_url_list"] as? Dictionary<String, AnyObject> {
            if let kkboxDlUrlArray = kkboxDlUrlDict["kkbox_dl_url"] as? NSArray {
                for dict in kkboxDlUrlArray {
                    if let name = dict["name"] as? String {
                        if name == mediaType.rawValue {
                            urlStr = dict["url"] as String
                        }
                    }
                }
            } else { return nil }
        } else { return nil }
    } else { return nil }

How do I shorten it to perhaps one or 2 line?

I realised I can chain it if it is 2 layers. This works:

 if let kkboxDlUrlArray = ticket["KKBOX"]?["kkbox_dl_url_list"] as? NSArray {

    }

But any chain longer than that, will not compile.

Is there a way to chain through a dictionary more than once?

Thank you


Solution

  • Seems like swift 1.2 has added this feature.

    "More powerful optional unwrapping with if let — The if let construct can now unwrap multiple optionals at once, as well as include intervening boolean conditions. This lets you express conditional control flow without unnecessary nesting."

    https://developer.apple.com/swift/blog/