There are lots useful of type, functions, protocols and classes in the Swift Standard Library, many of which have little or no documentation. After finding Swifter a website that extracts what little documentation exists, I have been trying to come up with example code demonstrating them. This is the first post in what I hope will be a series of posts.
Zip2
Given two sequences [ x0, x1 ... xn ] and [ y0, y1 ... yn ], Zip2 produces the sequence [ (x0, y0), (x1, y1) ... (xn, yn) ].
For example, suppose you are writing a Spanish verb conjugator, and you want to prepend the personal pronouns to each form of the verb, you could write:
1 2 3 4 5 6 |
var vs = [ "hablo", "hablas", "habla", "hablamos", "habláis", "hablan" ] let ps = [ "yo", "tú", "él/ella", "nosotros", "vosotros", "ellos/ellas"] let pv = map(Zip2(ps, vs)) { "\($0) \($1)" } pv |
Or if you are more mathematically minded you could implement a dot product routine:
1 2 3 4 5 6 7 8 |
var v1 = [ 1.0, 2.0, 3.0 ] var v2 = [ 3.0, 2.0, 1.0 ] func dot(v1 : [Double], v2: [Double]) -> Double { return map(Zip2(v1,v2), *).reduce(0.0, +) } dot(v1, v2) |
Download the Playground
The source for this and all other playgrounds in this series can be found on Github in the SwiftStandardLibraryPlaygrounds repository.