Skip to content

Instantly share code, notes, and snippets.

@peterkos
Last active June 16, 2016 01:19
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 peterkos/fe4acded03504bca8d87b5f060124378 to your computer and use it in GitHub Desktop.
Save peterkos/fe4acded03504bca8d87b5f060124378 to your computer and use it in GitHub Desktop.
Adds -=, /=, and *= operation to Strings in Swift.
func -= ( left: inout String, right: String) -> String {
let index = left.index(left.endIndex, offsetBy: -right.characters.count)
return left.substring(to: index)
}
func *= ( left: inout String, right: String) -> String {
var finalString = left
for _ in 0..<right.characters.count {
finalString.append(right)
}
return finalString
}
func /= ( left: inout String, right: String) -> String {
let count1 = Double(left.characters.count) / Double(right.characters.count)
let index = left.index(left.startIndex, offsetBy: Int(round(count1)))
return left.substring(to: index)
}
// Results!
var hello = "Hello"
var goodbye = "by"
hello -= goodbye // Hel
hello *= goodbye // Hellobyby
hello /= goodbye // Hel
hello += goodbye // Helloby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment