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.
As documentation said, COpaquePointer is a wrapper around an opaque C pointer.
Opaque pointers are used to represent C pointers to types that cannot be represented in Swift, such as incomplete struct types.
Key is a String - native Swift type. I believe that it is better to use this Swift String function:
let testString = "bla bli blah"
testString.stringByPaddingToLength(3, withString: " ", startingAtIndex: 0)
//output = "bla"
Swift 3
let testString = "bla bli blah"
testString.padding(toLength: 3, withPad: " ", startingAt: 0)
//output = "bla"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With