[swift unboxed]

Safely unboxing the Swift language & standard library


Function Types

A quick example of what function types look like in Swift.

2 June 2014 ∙ Swift Language ∙ written by

Function types:

  • Takes an int, returns an int: Int -> Int
  • Takes an int and a string, returns nothing: (Int, String) -> ()
  • No parameters, returns two doubles: () -> (Double, Double)

Functions are first class objects. Like C, function pointers have a particular type.

// takes an int, returns nothing
func sayHello(times: Int) {
  for i in (0..<times) {
    println("Hello")
  }
}

// pointer to a function that takes an int and returns nothing
var pointerToFunction: Int -> ()
pointerToFunction = sayHello

// Says hello 3 times
sayHello(3)
// Also says hello 3 times
pointerToFunction(3)