我们如何在 Swift 语言中创建唯一的对象列表,就像 Objective-C 中的 NSSet
和 NSMutableSet
一样。
最佳答案
从 Swift 1.2(Xcode 6.3 beta)开始,Swift 有一个原生的 set 类型。 来自发行说明:
A new
Set
data structure is included which provides a generic collection of unique elements, with full value semantics. It bridges withNSSet
, providing functionality analogous toArray
andDictionary
.
以下是一些简单的使用示例:
// 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")
}
但是还有更多可用的方法。
更新:集现在也记录在 "Collection Types" 中Swift 文档的章节。
关于swift - 如何在 Swift 中创建唯一对象列表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43191798/