简体   繁体   中英

Get all keys exists in NSDictionary and put into Array

在此处输入图像描述

When I snapshot from child "abc" I got this NSDictionary, "3c" can be added more nested childs. How can I get all the keys within an NSDictionary and put into Array Expected result: ["abc","1a","2b","3c"]

value.allkeys just take same hierarchy keys

As @AechoLiu writes a recursive approach is a nice way to go about it. Something like the below:

func nestedKeys(in dictionary: [String: Any]) -> [String] {
    guard let dictionaryValues = dictionary.values.filter({ $0 is [String: Any] }) as? [[String: Any]] else {
        return [String]() + dictionary.keys
    }
    let subKeys = dictionaryValues.reduce([String]()) { result, dictionary in
        return result + nestedKeys(in: dictionary)
    }
    return dictionary.keys + subKeys
}

The above expects your dictionaries to be of the format [String: Any] obviously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM