O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required