我的这个数组上有两个数组:
var myOptions: [[String:String]] = [
[
"1)About something": "some text here",
"2)Useful Advices": "some text here",
"3)Not to do": "some text here",
"4)Users Agreements": "some text here"
],
[
"5)About something else": "some text here",
"6)Useless Advices": "some text here",
"7)To do": "some text here",
"8)Non Users Agreements": "some text here"
]
]
我想创建一个新数组,只包含来自myOptions数组的键,其中的键仅存在于myOptions数组的第一个数组上。
所以要具体说明它可能是新的数组:
var keysOnly[String] = ["1)About something","2)Useful Advices","3)Not to do","4)Users Agreements"]
非常感谢你, Kostis
答案 0 :(得分:2)
您可以使用函数式编程轻松完成:
var keysOnly[String] = myOptions.flatMap({ return $0.keys })
//您编写的示例输出可能只是偶然或排序后,因为字典未被排序。你可以在一行中实现它,如:
var keys = myOptions.flatMap({ return $0.keys }).sorted(by: <)
答案 1 :(得分:1)
您有一个包含2个词典的数组。听起来你想要第一本字典中的键:
let keys = Array(myOptions[0].keys)
print(keys)
如果要组合2个词典中的键,并且想要对结果进行排序,可以使用@BencePattogato的答案:
var keys = myOptions.flatMap({ return $0.keys }).sorted(by: <)
但如果您的密钥包含不同位数的数字,您将无法获得预期的排序:
var myOptions: [[String:String]] = [
[
"1)About something": "some text here",
"2)Useful Advices": "some text here",
"3)Not to do": "some text here",
"4)Users Agreements": "some text here"
],
[
"5)About something else": "some text here",
"6)Useless Advices": "some text here",
"7)To do": "some text here",
"18)Non Users Agreements": "some text here"
]
]
var sortedKeys = myOptions.flatMap({ return $0.keys }).sorted(by: <)
会回来:
1)About something
18)Non Users Agreements
2)Useful Advices
3)Not to do
4)Users Agreements
5)About something else
6)Useless Advices
7)To do
(注意18和1之间的排序)
你可以改写这样的排序:
var sortedKeys = myOptions.flatMap({ return $0.keys })
.sorted{ $0.compare($1, options: .numeric) == .orderedAscending }
这会得到结果:
1)About something
2)Useful Advices
3)Not to do
4)Users Agreements
5)About something else
6)Useless Advices
7)To do
18)Non Users Agreements
这可能是你想要的。 (通过compare()
options
设置.numeric
使用Array<String>
,您可以告诉sorted()
BW = bwmorph(BW, 'diag')
方法将字符串中的数字组排序为数值。)