Skip to content

Instantly share code, notes, and snippets.

@fwgreen
Created April 2, 2023 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwgreen/449692362ac0edf2d4cec74d6887f178 to your computer and use it in GitHub Desktop.
Save fwgreen/449692362ac0edf2d4cec74d6887f178 to your computer and use it in GitHub Desktop.
A simple Swift version of Scala's mkString
extension Collection {
func makeString(_ separator: String) -> String { makeString("", separator, "") }
func makeString(_ prefix: String, _ separator: String, _ suffix: String) -> String {
if isEmpty {
return prefix + suffix
} else {
return addString("", prefix, separator, suffix)
}
}
private func addString(_ string: String, _ prefix: String, _ separator: String, _ suffix: String) -> String {
var string = string
if prefix.count != 0 { string.append(contentsOf: prefix) }
var it = makeIterator()
if let start = it.next() {
string.append(contentsOf: "\(start)")
while let rest = it.next() {
string.append(contentsOf: separator)
string.append(contentsOf: "\(rest)")
}
}
if suffix.count != 0 { string.append(contentsOf: suffix) }
return string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment