Created
September 6, 2014 15:57
-
-
Save rnapier/e0d91580d613fb21a52b to your computer and use it in GitHub Desktop.
Customer example from Flattenin' your mappenin'
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
struct Customer { | |
let name: String | |
let emails: [String] | |
} | |
let customers = [ | |
Customer(name: "Alice", emails: ["alice@example.com"]), | |
Customer(name: "Bob", emails: ["bob@example.org", "bobby@home.example"])] | |
let names = customers.map { $0.name } | |
names | |
let emails = customers.map { $0.emails } | |
emails | |
func flatten<T>(array: [[T]]) -> [T] { | |
var result = [T]() | |
for subarray in array { | |
result.extend(subarray) | |
} | |
return result | |
} | |
let flatEmails = flatten(customers.map { $0.emails }) | |
flatEmails | |
extension Array { | |
func flatMap<U>(transform: T -> [U]) -> [U] { | |
return flatten(self.map(transform)) | |
} | |
} | |
let flatMapEmails = customers.flatMap { $0.emails } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment