Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Conditional variadic argument list evaluation
let debugEnabled = true
// This makes it all a bit easier to read
typealias LazyVarArgClosure = @autoclosure () -> CVarArgType
func conditionallyLogSomething(messageFormat:@autoclosure () -> String, args:LazyVarArgClosure...) {
// If this is false, we do nothing
if debugEnabled {
// Go through the list of closures and invoke them all, to get an array of arguments
// compatibvle with va_list
let realArgs:[CVarArgType] = args.map { (lazyArg:LazyVarArgClosure) in
return lazyArg()
}
// Use a nested function to present a "curried" function with only one
// argument so we can pass it to withVaList
func curriedStringWithFormat(valist:CVaListPointer) -> String {
// We capture the messageFormat closure and call it when creating
// the formatted string
return NSString(format:messageFormat(), arguments:valist)
}
// Call the curried function with a va_list
var s = withVaList(realArgs, curriedStringWithFormat)
println(s)
}
}
func expensiveA() -> String {
println("EXPENSIVE A!")
return "Marc"
}
func expensiveB() -> Int {
println("EXPENSIVE B!")
return 41
}
conditionallyLogSomething("This is testing conditional %@ you are %lu years old", expensiveA(), expensiveB() )
@glaurent

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment