PeiSong PeiSong -4 years ago 220
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)


Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download