Last active
August 29, 2015 14:18
-
-
Save jbrownson/b11552b3b2ce0ddbfdcd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| func add5(i: Int) -> Int { return i + 5 } | |
| add5(42) | |
| // Arrays: The Hard Way | |
| func add5ArrayTheHardWay(array: [Int]) -> [Int] { | |
| var arrayAdd5 = [Int]() | |
| for i in array { arrayAdd5.append(add5(i)) } | |
| return arrayAdd5 | |
| } | |
| add5ArrayTheHardWay([1, 2, 3]) | |
| add5ArrayTheHardWay([]) | |
| add5ArrayTheHardWay([42]) | |
| // map | |
| [1, 2, 3].map(add5) | |
| [].map(add5) | |
| [42].map(add5) | |
| // Arrays: The Easy Way | |
| let add5Array: ([Int]) -> [Int] = {$0.map(add5)} | |
| add5Array([1, 2, 3]) | |
| add5Array([]) | |
| add5Array([42]) | |
| // Optionals: The Hard Way | |
| func add5OptionalTheHardWay(optional: Int?) -> Int? { | |
| if let a = optional { | |
| return add5(a) | |
| } | |
| return nil | |
| } | |
| add5OptionalTheHardWay(nil) | |
| add5OptionalTheHardWay(42) | |
| // Optionals: The Easy Way | |
| let add5Optional: (Int?) -> Int? = {$0.map(add5)} // Exactly the same as Array! | |
| add5Optional(nil) | |
| add5Optional(42) | |
| // Optionals are a lot like arrays that have either 0 or 1 elements | |
| // How do you use it? | |
| //add5("42".toInt()) // Doesn't typecheck! | |
| // This gets old | |
| var x: Int? = nil | |
| if let a = "42".toInt() { | |
| x = add5(a) | |
| } | |
| x | |
| // This is nicer | |
| add5Optional("42".toInt()) | |
| // It's so simple you can do it inline | |
| let inline = {$0.map(add5)}("42".toInt()) | |
| inline | |
| // .? is map for Optional on member functions | |
| extension Int { | |
| func add5() -> Int { return self + 5 } | |
| } | |
| 42.add5() | |
| let optionalInt: Int? = 42 | |
| optionalInt?.add5() | |
| let yy = (optionalInt?.add5())?.add5() | |
| let xx = (optionalInt.map {$0.add5()}).map {$0.add5()} | |
| (xx, yy) | |
| // Let's add an operator for non-member functions too | |
| infix operator <?> {} | |
| func <?><T, U>(l: (T) -> U, r: T?) -> U? { return map(r, l) } | |
| add5 <?> "42".toInt() | |
| add5 <?> (add5 <?> "42".toInt()) | |
| (add5 <?> (add5 <?> "42".toInt()))?.description | |
| // None of this works for functions with multiple arguments. There is a way to do it, but it's another talk. | |
| // If you're intrigued and want to learn more, research Functors |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can't get a selected language to stick so it's color coded for some reason