0

I have an array of dictionaries of type <Int,String> like this:

[14: "2", 17: "5", 6: "5", 12: "Ali", 11: "0", 2: "4", 5: "It it it", 15: "5", 18: "2", 16: "5", 8: "2", 13: "4", 19: "4", 1: "2", 4: "12-09-2017 - 9:52"]

I need to get the keys alone and save them in a string, and the values alone and save them in another string.

The results should look like that:

string key = "12,17,6,12,11,2,5,15,18,16,8,13,19,1,4"
string values = "2,5,5,Ali,0,4,It it ti,5,2,5,2,4,4,2,12-09-2017 - 9:52"
1
  • 3
    That's not an array of dictionaries. That just a single dictionary. Commented Sep 12, 2017 at 7:14

2 Answers 2

3

A dictionary has a keys and a values property which return the keys/values as a (lazy) collection. For the values you just have to join them:

let dict = [14: "2", 17: "5", 6: "5", 12: "Ali", 11: "0", 2: "4", 5: "It it it", 15: "5", 18: "2", 16: "5", 8: "2", 13: "4", 19: "4", 1: "2", 4: "12-09-2017 - 9:52"]

let values = dict.values.joined(separator: ",")
// Ali,5,2,It it it,5,0,4,5,4,4,2,12-09-2017 - 9:52,5,2,2

The keys are integers and must be converted to strings first:

let keys = dict.keys.map(String.init).joined(separator: ",")
// 12,17,14,5,15,11,13,16,19,2,18,4,6,8,1

The order is unspecified, but the same for keys and values.

Sign up to request clarification or add additional context in comments.

2 Comments

I was just about to post the same code. I was actually surprised the order of the keys and values match each other. Since a dictionary has no order, I would have guessed that the order of dict.value might be different than the order of dict.keys but they are the same within a given execution.
@rmaddy: Yes, the documentation states that "When iterated over, keys appear in this collection in the same order as they occur in the dictionary’s key-value pairs." and the same for the values, so they match as long as the dictionary is not modified. – At least that is my interpretation, this was also discussed at stackoverflow.com/questions/27353434/dictionary-key-value-order.
0

Try this, this can be refactored I am sure, this is the first logic that hit me.

let dictionary = [14: "2", 17: "5", 6: "5", 12: "Ali", 11: "0", 2: "4", 5: "It it it", 15: "5", 18: "2", 16: "5", 8: "2", 13: "4", 19: "4", 1: "2", 4: "12-09-2017 - 9:52"]


let arrayKeys = dictionary.map({ $0.key})
print(arrayKeys)

var stringValue: String = ""

for value in arrayKeys {
    stringValue.append(value.description)
    stringValue.append(",")
}

2 Comments

why you get arrayKeys by maping all keys in dictionary? there is dictionary.keys that do exactly what you want.
I was not aware of that. Thanks @pacification

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.