Cross-join two Swift arrays

Here is a Gist I just published on GitHub of a utility function that performs a cross-join between two Swift arrays. This allows you to iterate over one array for every element in another array, and return an optional value built for each pair of array elements.

This code was compiled and tested against Xcode 6 Beta 3.


extension Array
{
func crossJoin<E, R>(
array: [E],
joiner: (t: T, e: E) -> R?)
-> [R]
{
return arrayCrossJoin(self, array, joiner)
}
}
/**
Executes the `joiner` closure for every combination
of elements between `aArray` and `bArray` and returns
the resulting objects in the order they were created.
*/
func arrayCrossJoin<A, B, R>(
aArray: [A],
bArray: [B],
joiner: (a: A, b: B) -> R?)
-> [R]
{
var results = [R]()
for a in aArray
{
for b in bArray
{
if let result = joiner(a: a, b: b)
{
results.append(result)
}
}
}
return results
}
let letters = ["A", "B", "C"]
let numbers = [1, 2]
let dictionaries = letters.crossJoin(numbers) { [$0: $1] }
println(dictionaries)
// Prints: [[A: 1], [A: 2], [B: 1], [B: 2], [C: 1], [C: 2]]

view raw

CrossJoin.swift

hosted with ❤ by GitHub

This entry was posted in Swift and tagged , , . Bookmark the permalink.

1 Response to Cross-join two Swift arrays

  1. Pingback: Dew Drop – June 19, 2014 (#1800) | Morning Dew

Comments are closed.