Last active
August 29, 2015 14:02
-
-
Save debreuil/bc793e4b878fc3c0c6df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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