Skip to content

Instantly share code, notes, and snippets.

Last active Feb 3, 2018
What would you like to do?
Helper functions
import Foundation
/// This is going to be one of those things that for many of you is so obvious that it doesn't
/// require saying. But maybe a few of you have never really done this before either. I've been
/// thinking about nested helper functions.
/// I've used little nested helper functions lots of times. I do this when I want a function, but
/// nothing outside of this scope would ever need it.
func doSomething() {
func inc(x: Int) -> Int { return x + 1 }
/// And I've sometimes used the parameters to the outer function in the nested function, which is
/// often very handy. This is really common in Scala because you often need this for loops.
func doSomethingToX(x: Int) {
func incX() -> Int { return x + 1 }
/// But I've always created the helper function at the top. I'd never thought about setting a bunch
/// of things to be captured by the helper. For example, from a current project I'm playing with:
func solve(config: Config) throws {
let input = try config.parser(filename: config.filename)
// Here I set up the formatter
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [.Hour, .Minute, .Second]
// And here I set the start date
let startDate = NSDate()
// And *then* I define the helper function, which makes the rest of the code much simpler
func duration() -> NSString {
return formatter.stringFromDate(startDate, toDate: NSDate()) ?? ""
var bestSolution: Solution?
for solution in GeneratorSequence(config.makeSolutionGenerator(input)) {
bestSolution = solution
print("\(duration()) : \(solution.progressOutput)")
print("Final Time: \(duration())")
print(bestSolution?.finalOutput ?? "NO SOLUTION")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment