Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active March 10, 2016 21:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchytech/0ba6dfe2b197f188c64b to your computer and use it in GitHub Desktop.
Save sketchytech/0ba6dfe2b197f188c64b to your computer and use it in GitHub Desktop.
Seven Basics of Functional Programming in Swift
// one: use Swift's closure syntax to write a function as a value, either specifying type or being explicit about the values to be passed within the function
let squared:Int -> Int = {$0 * $0}
let squared = {(v:Int) in return v * v}
// two: you use the name of the variable or constant as the method name
squared(10) // 100
// three: functions are copied when assigned to new variables
var square = squared
square(10) // 100
// four: a variable function can have it's value changed as long as it is consistent with its original type
square = { $0 * $0 * $0}
// five: a function can return a function
let cubing: () -> (Int -> Int) = {{$0 * $0 * $0}}
let cube = cubing()
cube(2) // 8
// six: the function that returns a function can have an ongoing effect on the function that is returned
let cubingMultiplier: Int -> (Int -> Int) = {v in {$0 * $0 * $0 * v}}
let cubedMultipliedByThree = cubingMultiplier(3)
cubedMultipliedByThree(2) // 24
// seven: to tidy things up we can give function types meaningful names using typealias
typealias sodaPop = Int -> Float
let bubbles:sodaPop = {Float($0)}
// eight: this one's not so basic, but shows how you can take a function not written as a value and still utilise it
typealias HaveFun = Int -> (Int -> Int)
func preExistingFunc(num:Int) -> Int { return num * num }
let myFunction:HaveFun = {v in { preExistingFunc($0*v) }}
let newFunc = myFunction(10)
newFunc(10) // 10000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment