Hello, Swift!
Let’s get a feel for Swift with a concrete example. It’s traditional to start with “hello world,” but to demonstrate functional programming, it makes more sense to start with the factorial function.
| func fact(n: Int) -> Int { |
| if n == 0 { |
| return 1 |
| } else { |
| return n * fact(n - 1) |
| } |
| } |
| |
| let x = fact(10) |
| println("The factorial of 10 is \(fact(10))") |
This code is pretty unsurprising. The only thing that’s at all unusual is that if you look inside the println, you can see that Swift does string interpolation: if you put \ (expression) into a string, then the result of that expression is converted into a string, and inserted into the enclosing string. That’s been common in scripting languages for a long time, but it hasn’t ...
Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.