Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

swift - Is there a zip function to create tuples with more than 2 elements?

I just discovered the Swift zip function recently. It seems quite useful.

It takes 2 input arrays and creates an array of tuples out of pairs of values from each array.

Is there a variant of zip that takes an arbitrary number of arrays and outputs tuples with that same number of elements? It seems like there should be a way to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Bear in mind, you can nest one zip inside another, and then unpack it with a nested tuple:

let integers = [1, 2, 3, 4, 5]
let strings = ["a", "b", "c", "d", "e"]
let doubles = [1.0, 2.0, 3.0, 4.0, 5.0]

for (integer, (string, double)) in zip(integers, zip(strings, doubles)) {
    print("(integer) (string) (double)")
}

Not quite as elegant as having a zip for arbitrary n-tuples, but it gets the job done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...