swift - 如何在 Swift 中创建唯一对象列表数组

标签 swift nsset

我们如何在 Swift 语言中创建唯一的对象列表,就像 Objective-C 中的 NSSetNSMutableSet 一样。

最佳答案

从 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 with NSSet, providing functionality analogous to Array and 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")
}

但是还有更多可用的方法。

更新:集现在也记录在 "Collection Types" 中Swift 文档的章节。

关于swift - 如何在 Swift 中创建唯一对象列表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43191798/

相关文章:

ios - 如何从一个数组中获得具有其他属性的对象?

ios - NSSet 计数后没用?

ios - 向下滚动时如何使 UIButton 在表格 View 中保持选中状态

java - 使用 ANTLR 4.7 : need to parse fragments in string literals 解析 Swift

swift - 用颜色填充 map 中的区域

ios - 使用 NSSet 从 NSMutableArray 中删除重复项

objective-c - 如何从包含任意对象的 NSSet 创建排序的 NSArray?

ios - 使用Swift的iOS Shoutcast访问元数据

ios - 无法在 Swift xcode 6.3.1 中使用类型为 'functionName' 的参数列表调用 '([(nameOfClass)])'

objective-c - NSNumbers 的 NSSet - 成员方法始终为 nil