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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]] |
Pingback: Dew Drop – June 19, 2014 (#1800) | Morning Dew