Skip to content

Instantly share code, notes, and snippets.

@Xvezda
Last active December 4, 2018 08:48
Show Gist options
  • Save Xvezda/aff1c88c38fe13a385e3ead006f4d27e to your computer and use it in GitHub Desktop.
Save Xvezda/aff1c88c38fe13a385e3ead006f4d27e to your computer and use it in GitHub Desktop.
How to repeat or duplicate word in Swift by using extension
/* Copyright (C) 2018 Xvezda <https://xvezda.com/> */
/* MIT License */
extension String {
func again(count: Int, with: String=" ") -> String {
if count <= 0 { // Ignore when count is less then zero.
return self
}
var stringBuilder = self
for _ in 0..<count {
stringBuilder.append(with+self)
}
return stringBuilder
}
}
print("Hello".again(count: 2, with: ", ")) // Hello, Hello, Hello
print("Hi".again(count: 1)) // Hi Hi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment