[英]Swift: How does zip() handle two different sized collections?
The zip() function takes two sequences and returns a sequence of tuples following: zip() 函数接受两个序列并返回以下元组序列:
output[i] = (sequence1[i], sequence2[i])
However, the sequences can potentially be of different dimensions.然而,这些序列可能具有不同的维度。 My question is how does the Swift language deal with this?
我的问题是 Swift 语言如何处理这个问题?
The docs were utterly useless. 文档完全没用。
Seems to me, there are two possibilities (in Swift):在我看来,有两种可能性(在 Swift 中):
Swift uses the first option, the resulting sequence will have a length equal to the shorter of the two inputs . Swift使用第一个选项, 结果序列的长度等于两个输入中较短的一个 。
For example: 例如:
let a: [Int] = [1, 2, 3]
let b: [Int] = [4, 5, 6, 7]
let c: [(Int, Int)] = zip(a, b) // [(1, 4), (2, 5), (3, 6)]
Apple's zip(_:_:)
documentation has since been updated to answer this question: Apple 的
zip(_:_:)
文档已经更新以回答这个问题:
https://developer.apple.com/documentation/swift/1541125-zip https://developer.apple.com/documentation/swift/1541125-zip
If the two sequences passed to
zip(_:_:)
are different lengths, the resulting sequence is the same length as the shorter sequence .如果传递给
zip(_:_:)
的两个序列长度不同,则生成的序列与较短的序列长度相同。 In this example, the resulting array is the same length aswords
:在此示例中,结果数组的长度与
words
相同:let words = ["one", "two", "three", "four"] let naturalNumbers = 1...Int.max let zipped = Array(zip(words, naturalNumbers)) // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.