Swift 设置为数组 [英] Swift Set to Array
本文介绍了Swift 设置为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
NSSet
可以使用 set.allObjects()
转换为 Array
但在新的 Set 中没有这样的方法
(在 Swift 1.2 中引入).它仍然可以通过将 Swift Set 转换为 NSSet 并使用 allObjects()
方法来完成,但这不是最佳的.
An NSSet
can be converted to Array
using set.allObjects()
but there is no such method in the new Set
(introduced with Swift 1.2). It can still be done by converting Swift Set to NSSet and use the allObjects()
method but that is not optimal.
推荐答案
您可以创建一个包含来自给定 Swift 的所有元素的数组Set
只需用
You can create an array with all elements from a given Swift
Set
simply with
let array = Array(someSet)
这是可行的,因为 Set
符合 SequenceType
协议并且 Array
可以用序列初始化.示例:
This works because Set
conforms to the SequenceType
protocol
and an Array
can be initialized with a sequence. Example:
let mySet = Set(["a", "b", "a"]) // Set<String>
let myArray = Array(mySet) // Array<String>
print(myArray) // [b, a]
这篇关于Swift 设置为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文