Remove nested key from dictionary

前端 未结 5 1858
抹茶落季
抹茶落季 2020-12-20 16:07

Let\'s say I have a rather complex dictionary, like this one:

let dict: [String: Any] = [
    \"countries\": [
        \"japan\": [
            \"capital\":          


        
5条回答
  •  感情败类
    2020-12-20 16:40

    Pass your dictionary to this function, It will return you a flat dictionary, without any nested dict incorporated .

    //SWIFT 3.0

    func concatDict( dict: [String: Any])-> [String: Any]{
            var dict = dict
            for (parentKey, parentValue) in dict{
                if let insideDict = parentValue as? [String: Any]{
                    let keys = insideDict.keys.map{
                        return parentKey + $0
                    }
                    for (key, value) in zip(keys, insideDict.values) {
                        dict[key] = value
                    }
                    dict[parentKey] = nil
                    dict = concatDict(dict: dict)
                }
            }
            return dict
        }
    

提交回复
热议问题