How to convert dictionary to array

后端 未结 5 1680
闹比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:05

    You will have to go through and construct a new array yourself from the keys and the values.

    Have a look at 's swift array documentation:

    You can add a new item to the end of an array by calling the array’s append(_:) method:

    Try this:

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

    Have a look at What's the cleanest way of applying map() to a dictionary in Swift? if you're using Swift 2.0:

提交回复
热议问题