Skip to content

Instantly share code, notes, and snippets.

@debreuil
Last active August 29, 2015 14:02
Show Gist options
  • Save debreuil/bc793e4b878fc3c0c6df to your computer and use it in GitHub Desktop.
Save debreuil/bc793e4b878fc3c0c6df to your computer and use it in GitHub Desktop.
// What are nested and curried functions? How do you use them in Swift?
// nesting/currying allows piping function calls together like fn(1)(2)(3)
// multiple functions, requires fnA(1) + fnB(2) + fnC(3) syntax
func daysToSeconds(days:Int)->Int {
return days * 24 * 60 * 60
}
func hoursToSeconds(hours:Int)->Int {
return hours * 60 * 60
}
func minutesToSeconds(minutes:Int)->Int {
return minutes * 60
}
// just call each function and add the results
let s1 = daysToSeconds(5) + hoursToSeconds(4) + minutesToSeconds(35) // 448,500
// nested functions
// this is a function that returns a function that returns a function
// allows the syntax fn(1)(2)(3), but is somewhat verbose
func daysHoursMinutesToSeconds(days:Int)->(Int -> (Int -> Int)) {
func hours(hours:Int)->(Int -> Int) {
func minutes(minutes:Int)->Int {
// the nested functions have access to the wrapped parameters
return days * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60
}
return minutes
}
return hours
}
// calls can now be nested, calling on the returned function directly
let s2 = daysHoursMinutesToSeconds(5)(4)(35) // 448,500
// curried functions
// functionally equivilent to the nested version above, allows fn(1)(2)(3)
func toSeconds(#days:Int)(hours:Int)(minutes:Int)->Int {
return days * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60
}
let s3 = toSeconds(days:5)(hours:4)(minutes:35) // 448,500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment