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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…