#Repeating Strings
Repeating Strings
Unfortunately, Swift does not support String multiplication with *
, likewise Python. A good method you can use instead is String(repeating:count:)
, but unfortunately that's not really golfy. Compare these two approaches:
var a=String(repeating:"abc",count:3)
and
var a="";for _ in 0..<3{a+="abc"}
The second one is a couple of bytes shorter, but that cannot be used in a closure... Better yet, and it also works in closures:
(0..<3).map{_ in"abc"}.joined()
And what if I do it multiple times? Well, you can use String.init()
. Now, this may save lots of bytes. For example (68 bytes):
let k=String.init(repeating:count:)
print(k("abcd",9)+k("XYZxyz",9))
instead of (74 bytes):
print(String(repeating:"abcd",count:9)+String(repeating:"XYZxyz",count:9))
or (70 bytes):
var f={String(repeating:$0,count:$1)}
print(f("abcd",9)+f("XYZxyz",9))
But make sure your String is long enough. If you are using String(repeating:"abc",3)
, it is much better to use "abcabcabc"
instead.