当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Swift Set init(_:)用法及代码示例

用法一

初始化器

init(_:)

从有限的项目序列创建一个新集合。

声明

init<Source>(_ sequence: Source) where Element == Source.Element, Source : Sequence
Element 符合 Hashable 时可用。

参数

sequence

用作新集合成员的元素。

详述

使用此初始化程序从现有序列(例如数组或范围)创建新集合。


let validIndices = Set(0..<7).subtracting([2, 4, 5])
print(validIndices)
// Prints "[6, 0, 1, 3]"

此初始化器还可用于在对集合执行 filter(_:)map(_:) 等序列操作后恢复集合方法。例如,在过滤一组素数以删除任何低于 10 的素数后,您可以使用此初始化程序创建一个新集合。


let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23]
let laterPrimes = Set(primes.lazy.filter { $0 > 10 })
print(laterPrimes)
// Prints "[17, 19, 23, 11, 13]"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

用法二

初始化器

init(_:)

从有限的项目序列创建一个新集合。

声明

init<S>(_ sequence: S) where S : Sequence, Self.Element == S.Element

参数

sequence

用作新集合成员的元素。

详述

使用此初始化程序从现有序列(如数组或范围)创建新集合:


let validIndices = Set(0..<7).subtracting([2, 4, 5])
print(validIndices)
// Prints "[6, 0, 1, 3]"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Set init(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。