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


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

函数

zip(_:_:)

创建由两个基础序列构建的对序列。

声明

func zip<Sequence1, Sequence2>(
    _ sequence1: Sequence1,
    _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence

返回值

元组对的序列,其中每对的元素是 sequence1sequence2 的对应元素。

参数

sequence1

要压缩的第一个序列或集合。

sequence2

要压缩的第二个序列或集合。

详述

在此函数返回的Zip2Sequence 实例中,第i 对的元素是每个底层序列的第i 元素。以下示例使用 zip(_:_:) 函数同时迭代字符串数组和可数范围:


let words = ["one", "two", "three", "four"]
let numbers = 1...4


for (word, number) in zip(words, numbers) {
    print("\(word): \(number)")
}
// Prints "one: 1"
// Prints "two: 2
// Prints "three: 3"
// Prints "four: 4"

如果传递给zip(_:_:) 的两个序列长度不同,则生成的序列与较短序列的长度相同。在此示例中,结果数组的长度与 words 相同:


let naturalNumbers = 1...Int.max
let zipped = Array(zip(words, naturalNumbers))
// zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]

可用版本

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

相关用法


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