Padding. Sometimes a String needs to be a certain number of characters long. It must fill an entire text field. With padding methods, we can add characters to a String.
In Foundation, we find a method called padding() with 3 arguments. We specify a string that is added to fill the desired length. This pads a string.
First example. To begin, we introduce a String that has 4 characters (cats). We then invoke the padding() method. We use 3 arguments.
Info We pass 10 to expand the string to a width of 10 characters. The resulting string will have 10 chars in its padded form.
And This string is used to create the padding. It is repeated to fill the desired length.
// An example string.
let cats = "cats"// Pad to length 10.
let padded = cats.padding(toLength: 10, withPad: " ", startingAt: 0)
// Write result.
print("Padded = |\(padded)|")Padded = |cats |
Different characters. With the padding() method, we can pad with different characters. A space is a common padding char, but here we use a hyphen to pad a string.
// A string.
let id = "X1"// Pad with hyphens.
let padded = id.padding(toLength: 4, withPad: "-", startingAt: 0)
// Uses hyphen as padding character.
Some notes. In Swift, strings can be hard to manipulate. But we usually do best by choosing the most specific Foundation method possible.
And We could apply padding by adding space chars, but this is more complex. A single Foundation call is clearer.
Swift 3 changes. In Swift 3 we use padding() instead of stringByPaddingToLength. The method call is simpler, and the arguments are labeled differently.
Padding increases the length of a String to fill a field. This can be used to ensure a string meets a length requirement. It can be used sometimes for text justification.