# [Swift]Set(集)转换为Array(数组)

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号：山青咏芝（shanqingyongzhi）
➤博客园地址：山青咏芝（https://www.cnblogs.com/strengthen/
➤GitHub地址：https://github.com/strengthen/LeetCode
➤原文地址：https://www.cnblogs.com/strengthen/p/10176725.html
➤如果链接不是山青咏芝的博客园地址，则可能是爬取作者的文章。
➤原文已修改更新！强烈建议点击原文地址阅读！支持作者！支持原创！
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

1 //Set排序
2 let stringSet1 = Set(["car", "boat", "bike", "toy"])
3 let stringArray1 = stringSet1.sorted()
4 print(stringArray1)
5 // will print ["bike", "boat", "car", "toy"]
6
7 //Set去除元素第一位不为b字母的元素
8 let stringSet2 = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")
9 let stringArray2 = stringSet2.filter { $0.characters.first != "b" } 10 print(stringArray2) 11 // may print ["car", "toy"] 12 13 //Set<Int>转换为[String] 14 let intSet3 = Set([1, 3, 5, 2]) 15 //方法一：flatMap 16 let stringArray3 = intSet3.flatMap { String($0) }
17 print(stringArray3)
18 //方法二：Array
19 let stringArray4 = Array(intSet3)
20 print(stringArray4)
21 // may print ["5", "2", "3", "1"]
22
23 //Set<Int>转换为[Int]
24 let intSet5 = Set([1, 3, 5, 2])
25 let intArray5 = intSet5.map { \$0 }
26 print(intArray5)
27 // may print [5, 2, 3, 1]

posted @ 2018-12-25 21:58  山青咏芝  阅读(750)  评论(0编辑  收藏