Created
June 9, 2016 23:04
ZipWithKeySwift
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
//: 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