PeiSong PeiSong - 3 months ago 19
Swift Question

How can I format string with fixed length in swift

For example:
var str = String(format: "%12s - %s", "key", "value")

What I want is key will hold chars of length of 12.
key__________ - value

(underscore here is whitespace)

Thanks.

Answer

Basically, to format String with String(format: _:...), we can use %@:

String(format: "%@ - %@", "key", "value")

But, I believe %@ does not support "width" modifier: you cannot %12@ or such.

So, you have to convert String to COpaquePointer which can be formatted with %s:

var key = "key"
var val = "value"

var str = String(format: "%-12s - %s",
    COpaquePointer(key.cStringUsingEncoding(NSUTF8StringEncoding)!),
    COpaquePointer(val.cStringUsingEncoding(NSUTF8StringEncoding)!)
)
// -> "key          - value"
Comments