Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Created June 9, 2016 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ben-G/236cdfed80ed5ed7271f90240cc57b10 to your computer and use it in GitHub Desktop.
Save Ben-G/236cdfed80ed5ed7271f90240cc57b10 to your computer and use it in GitHub Desktop.
ZipWithKeySwift
//: Playground - noun: a place where people can play
import UIKit
struct Person {
let name: String
let age: Int
}
struct Car {
let owner: String
let license: String
}
let persons = [Person(name: "Benji", age: 20), Person(name: "Jaron", age: 32)]
let cars = [Car(owner: "Jaron", license: "JXYZ"), Car(owner: "Benji", license: "XYZ")]
func zipWithKey<Type1, Type2, KeyType: Hashable>(
array1: [Type1],
array2: [Type2],
keyFunction1: (Type1) -> KeyType,
keyFunction2: (Type2) -> KeyType
) -> [(Type1, Type2)] {
var hashTable: [KeyType: Type1] = [:]
for element in array1 {
hashTable[keyFunction1(element)] = element
}
var result: [(Type1, Type2)] = []
for element in array2 {
guard let type1Counterpart = hashTable[keyFunction2(element)] else {
continue
}
result.append((type1Counterpart, element))
}
return result
}
let x = zipWithKey(persons, array2: cars, keyFunction1: { $0.name }, keyFunction2: { $0.owner })
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment