Created
April 2, 2023 04:40
-
-
Save fwgreen/449692362ac0edf2d4cec74d6887f178 to your computer and use it in GitHub Desktop.
A simple Swift version of Scala's mkString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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