Create a string with n blank spaces or other repeated character

String already has a repeating:count: initializer just like Array (and other collections that adopt the RangeReplaceableIndexable protocol):

init(repeating repeatedValue: String, count: Int)

So you can just call:

let spaces = String(repeating: " ", count: 5) // -> "     "

Notice that the repeated parameter is a string, not just a character, so you can repeat entire sequences if you want:

let wave = String(repeating: "-=", count: 5) // -> "-=-=-=-=-="

Edit: Changed to Swift 3 syntax and removed discussion of Swift 1 type ambiguity issues. See the edit history if you need to work with old versions.


In Swift 3:

var s = String(repeating: " ", count: 5)

https://developer.apple.com/reference/swift/string/2427723-init


I think we can play with stringbyPaddingToLength

something like this should work:

var str = " ";
var str2 = str.stringByPaddingToLength(20, withString: " ", startingAtIndex: 0);

Tags:

String

Ios

Swift