Victor Sigler Victor Sigler - 9 months ago 35
Swift Question

Create a string with n blank spaces or other repeated character

I want to make a string with n blank spaces using Swift, but without using a

loop or manually like this:

// string with 5-blank space
var s = " "


String already has the same count:repeatedValue: initializer as Array:

init(count sz: Int, repeatedValue c: Character)

So you can just call:

let spaces = String(count: 5, repeatedValue: (" " as Character))

You have to clarify that the string literal passed in is a Character literal, because otherwise the type inference is ambiguous. There's another initializer that takes a UnicodeScalar, and a string literal can automatically convert to either Character or UnicodeScalar. You can get around the as (or Character(" ")) business if you're in a context where the type of the string literal can be uniquely inferred.

For example, if you like Python's way of repeating strings (I won't judge):

func *(lhs: Character, rhs: Int) -> String {
    return String(count: rhs, repeatedValue: lhs)
let s = " " * 5

This only works for Character operands, so the type passed through to repeatedValue is unique.