Skip to content

Instantly share code, notes, and snippets.

@tidwall
Last active August 29, 2015 14:18
Show Gist options
  • Save tidwall/832e548871faaabd7cd7 to your computer and use it in GitHub Desktop.
Save tidwall/832e548871faaabd7cd7 to your computer and use it in GitHub Desktop.
C Style Formatting for Swift
func formatv(fstr : String, args : [CVarArgType]) -> String{
var (res, af, i) = ("", "", 0)
for c in fstr {
if af == "" {
if c == "%"{
af = "%"
} else {
res += String(c)
}
} else {
if c == "%"{
if af == "%"{
af = ""
res += "%"
continue
}
}
var lc = c
switch c {
case "s","@","d","i","u","o","x","X","f","F","e","E","g","G","a","A","c","p","n","v","j","J":
break
default:
af += String(c)
continue
}
if i < count(args){
if lc == "j" || lc == "J" {
let indent = lc == "J"
if var jo: AnyObject = args[i++] as? AnyObject{
if NSJSONSerialization.isValidJSONObject(jo) {
if let data = NSJSONSerialization.dataWithJSONObject(jo, options: (indent ? NSJSONWritingOptions.PrettyPrinted : nil), error: nil) {
if let str = NSString(bytes: UnsafePointer<Int8>(data.bytes), length: data.length, encoding: NSUTF8StringEncoding){
res += str as String
af = ""
continue
}
}
}
}
res += "?"
} else if lc == "s" {
if let so = args[i++] as? NSString{
var data = NSMutableData(data: so.description.dataUsingEncoding(NSUTF8StringEncoding)!)
data.appendBytes("\0", length: 1)
res += String(format:af+String("s"), data.bytes)
}
} else {
res += String(format:af+String(lc), args[i++])
}
} else {
res += "?"
}
af = ""
}
}
return res
}
func format(fstr : String, args : CVarArgType ...) -> String{
return formatv(fstr, args)
}
func fprint(fstr : String, args : CVarArgType ...) {
print(formatv(fstr, args))
}
func fprintln(fstr : String, args : CVarArgType ...) {
println(formatv(fstr, args))
}
@tidwall
Copy link
Author

tidwall commented Apr 9, 2015

Standard C-style format specifiers for Swift.

Features

  • String, NSString, Printable can be formatted using %s.
  • JSON can be using %j. %J will indent the JSON. Only Arrays and Dictionaries are supported.

Examples

fprintln("Hello %s", "Tom")
let output = format("Touch %d times.", 15)
fprintln("JSON output: %j", ["Age":28,"Name":"Tom Tom"])

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