I want to make a string with n blank spaces using Swift, but without using a for
loop or manually like this:
// string with 5-blank spa
2020 | SWIFT 3.0 - 5.1:
I like syntax of c# for doing this action. So I wrote an extension:
static func * (str: String, repeatTimes: Int) -> String {
return String(repeating: str, count: repeatTimes)
}
and now you're able to do this by the following way:
let tenSpaces = " " * 10
let ab15Times = "ab" * 15
I think we can play with stringbyPaddingToLength
something like this should work:
var str = " ";
var str2 = str.stringByPaddingToLength(20, withString: " ", startingAtIndex: 0);
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