Sean Cook Sean Cook - 4 months ago 12
Swift Question

Swift formatting a string to a certain length

I have a series of string that I need to print on 1 line.

var qty: Int = 1
var name: "Book"
var price: 13.50


I need each to have blank space appended to them so they are a certain length or have characters removed if they are too long. For the qty id like it to be a length of 3, name 30 and price 8

Format should be

1 Book 13.50

Answer

There is a much better, Swift-like solution:

String(qty).stringByPaddingToLength(3, withString: " ", startingAtIndex: 0)

name.stringByPaddingToLength(30, withString: " ", startingAtIndex: 0)

String(price).stringByPaddingToLength(8, withString: " ", startingAtIndex: 0)

According to Apple documentation:

Returns a new string formed from the receiver by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.

So that's what you need.

The usage can be something as this:

let output = String(qty).stringByPaddingToLength(3, withString: " ", startingAtIndex: 0) + name.stringByPaddingToLength(30, withString: " ", startingAtIndex: 0) + String(price).stringByPaddingToLength(8, withString: " ", startingAtIndex: 0)

UPDATE:

In order to pad to the right:

let p = String(price)
"".stringByPaddingToLength(8 - p.characters.count, withString: " ", startingAtIndex: 0) + p
Comments