Skip to content

Instantly share code, notes, and snippets.

@lilyball
Created June 19, 2014 02:50
Show Gist options
  • Save lilyball/c4a62d7f82df0afffc9a to your computer and use it in GitHub Desktop.
Save lilyball/c4a62d7f82df0afffc9a to your computer and use it in GitHub Desktop.
import Darwin
// Uses printf() formatting
// Returns String! because vasprintf() can fail to allocate
func Format(fmt: String, args: CVarArg...) -> String! {
var chars: UnsafePointer<CChar> = nil
let n = withUnsafePointer(&chars) {
charp in
withVaList(args) {
va_list in
fmt.withCString { vasprintf(charp, $0, va_list) }
}
}
if n < 0 {
// vasprintf failed to allocate
return nil
}
let s = String.fromCString(chars)
free(chars)
return s
}
println(Format("test: %04d", 3 as Int32))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment