Mar*_*n R 51
从Swift 1.2(Xcode 6.3 beta)开始,Swift有一个原生集类型.从发行说明:
Set包含一个新的数据结构,它提供了具有完整值语义的唯一元素的通用集合.它与之桥接NSSet,提供类似于Array和的功能Dictionary.
以下是一些简单的用法示例:
// Create set from array literal:
var set = Set([1, 2, 3, 2, 1])
// Add single elements:
set.insert(4)
set.insert(3)
// Add multiple elements:
set.unionInPlace([ 4, 5, 6 ])
// Swift 3: set.formUnion([ 4, 5, 6 ])
// Remove single element:
set.remove(2)
// Remove multiple elements:
set.subtractInPlace([ 6, 7 ])
// Swift 3: set.subtract([ 6, 7 ])
print(set) // [5, 3, 1, 4]
// Test membership:
if set.contains(5) {
print("yes")
}
Run Code Online (Sandbox Code Playgroud)
但是有更多的方法可供选择.
更新:集合现在也记录在Swift文档的"集合类型"一章中.
Aus*_*tin 14
您可以在Swift中使用任何Objective-C类:
var set = NSMutableSet()
set.addObject(foo)
Run Code Online (Sandbox Code Playgroud)
Tom*_*rdt 10
斯威夫特没有集合的概念.NSMutableSet在Swift中使用可能比使用Dictionary包含虚拟值的更慢.你可以这样做:
var mySet: Dictionary<String, Boolean> = [:]
mySet["something"]= 1
Run Code Online (Sandbox Code Playgroud)
然后只是遍历键.
我已经建立了广泛的Set类似于内置式Array和Dictionary-这里的博客文章一和二和GitHub的库:
extension Array where Element: Hashable {
var setValue: Set<Element> {
return Set<Element>(self)
}
}
let numbers = [1,2,3,4,5,6,7,8,9,0,0,9,8,7]
let uniqueNumbers = numbers.setValue // {0, 2, 4, 9, 5, 6, 7, 3, 1, 8}
let names = ["John","Mary","Steve","Mary"]
let uniqueNames = names.setValue // {"John", "Mary", "Steve"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46227 次 |
| 最近记录: |