How to convert dictionary to array

后端 未结 5 1721
闹比i
闹比i 2020-12-28 12:06

I want to convert my dictionary to an array, by showing each [String : Int] of the dictionary as a string in the array.

For example:     



        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 13:07

    You can use a for loop to iterate through the dictionary key/value pairs to construct your array:

    var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12]
    
    var arr = [String]()
    
    for (key, value) in myDict {
        arr.append("\(key) \(value)")
    }
    

    Note: Dictionaries are unordered, so the order of your array might not be what you expect.


    In Swift 2 and later, this also can be done with map:

    let arr = myDict.map { "\($0) \($1)" }
    

    This can also be written as:

    let arr = myDict.map { "\($0.key) \($0.value)" }
    

    which is clearer if not as short.

提交回复
热议问题