函數
zip(_:
zip(_:_:)
創建由兩個基礎序列構建的對序列。
聲明
func zip<Sequence1, Sequence2>(
_ sequence1: Sequence1,
_ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence
返回值
元組對的序列,其中每對的元素是 sequence1 和 sequence2 的對應元素。
參數
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+
相關用法
- Swift KeyValuePairs flatMap(_:)用法及代碼示例
- Swift String.UTF8View first用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Int8 ~(_:)用法及代碼示例
- Swift SetAlgebra isStrictSubset(of:)用法及代碼示例
- Swift UInt +(_:)用法及代碼示例
- Swift Array enumerated()用法及代碼示例
- Swift FlattenSequence prefix(_:)用法及代碼示例
- Swift Slice endIndex用法及代碼示例
- Swift LazySequence split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift MutableCollection partition(by:)用法及代碼示例
- Swift ReversedCollection min(by:)用法及代碼示例
- Swift RandomNumberGenerator用法及代碼示例
- Swift Dictionary.Keys shuffled()用法及代碼示例
- Swift AnySequence elementsEqual(_:)用法及代碼示例
- Swift UInt &<<(_:_:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift DefaultIndices endIndex用法及代碼示例
- Swift Substring.UnicodeScalarView insert(contentsOf:at:)用法及代碼示例
- Swift LazyFilterSequence dropFirst(_:)用法及代碼示例
- Swift LazySequence suffix(from:)用法及代碼示例
- Swift ArraySlice starts(with:)用法及代碼示例
- Swift Int16.Words max()用法及代碼示例
- Swift ArraySlice reduce(_:_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 zip(_:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
