Iterate Dictionary with dictionary data and add it to an array in swift

后端 未结 2 1711
执念已碎
执念已碎 2020-12-20 00:43

I have a dictionary with multiple dictionary data :

{
    1455201094707 =     {
    };
    1455201116404 =     {
    }: 
    1455201287530 =     {
    };
}
         


        
相关标签:
2条回答
  • 2020-12-20 01:09

    First of all, when you use

    for let tempDict in dataDictionary {
         self.tempArray.addObject(tempDict)
    }
    

    Swift gives you tuple like (key, value) in tempDict.

    So you should iterate like this

    for (key, value) in sourceDict {
         tempArray.append(value)
    }
    

    Note: I used here native swift structures, and my advise - to use them as often as possible (instead of ObjC ones)

    Or you can use map-function on dictionary.

    let array = sourceDict.map({ $0.1 })
    

    Edit. For

    (
      {
        1455201094707 =     {
        };
      }
      {
         1455201116404 =     {
         }:
      } 
    ) 
    

    use

    for (key, value) in sourceDict {
         tempArray.append([key : value])
    }
    

    or

    let array = dict.map({ [$0.0 : $0.1] })
    

    Note. if you use NSDictionary you should cast it to swift Dictionary

    if let dict = dict as? [String: AnyObject] {
        let array = dict.map({ [$0.0 : $0.1] })
        print(array)
    }
    
    0 讨论(0)
  • 2020-12-20 01:12
    1. Get all keys from the dictionary, for this NSDictionary has property allKeys.

    2. Loop all keys, and add object for the key to the array.

    3. Before the all steps above, read documentation!

    Good luck!

    0 讨论(0)
提交回复
热议问题