PeiSong PeiSong - 6 months ago 34
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)



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",
// -> "key          - value"