Skip to content

Instantly share code, notes, and snippets.

@edwardIshaq
Last active December 2, 2015 20:02
Show Gist options
  • Save edwardIshaq/0264f993e75abdc5f4b3 to your computer and use it in GitHub Desktop.
Save edwardIshaq/0264f993e75abdc5f4b3 to your computer and use it in GitHub Desktop.
Swift Array Extension to Map & Filter on Element instance functions
extension Array {
func mapSelf<T>(f: Element -> () -> T) -> [T] {
return self.map{ f($0)() }
}
func filterSelf(includedElem: Element -> () -> Bool) -> [Element] {
return self.filter{ includedElem($0)() }
}
}
struct Person {
let name: String
func isEddie() -> Bool {
return name == "Eddie"
}
func greet() -> String {
return "Hello \(name)"
}
}
let me = Person(name: "Eddie")
me.isEddie()
let x = me.greet()
let tony = Person(name: "Tony")
let bros = [me, tony]
let greets = bros.map { (p: Person) -> String in
p.greet()
}
Person.greet(me)
let greets2 = bros.map{ Person.greet($0)()}
print(greets2)
Person.greet
let yaay1 = bros.mapSelf(Person.greet)
let yaay2 = bros.filterSelf(Person.isEddie)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment