Last active
August 29, 2015 14:18
-
-
Save tidwall/832e548871faaabd7cd7 to your computer and use it in GitHub Desktop.
C Style Formatting for Swift
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
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Standard C-style format specifiers for Swift.
Features
String
,NSString
,Printable
can be formatted using%s
.%j
.%J
will indent the JSON. Only Arrays and Dictionaries are supported.Examples