从字典数组中获取元素并将键保存为字符串,将值保存为字符串

时间:2017-09-12 07:12:06

标签: arrays swift dictionary

我有一组类型为<Int,String>的字典数组:

[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"]

我需要单独获取密钥并将它们保存在字符串中,并且仅将值保存在另一个字符串中。

结果应如下:

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"

2 个答案:

答案 0 :(得分:3)

字典有一个keys和一个values属性返回 键/值作为(懒惰)集合。对于你刚才拥有的价值观 加入他们:

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

键是整数,必须先转换为字符串:

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

订单未指定,但键和值相同。

答案 1 :(得分:0)

试试这个,这可以重构我相信,这是第一个打击我的逻辑。

$