Last active
June 16, 2016 01:19
-
-
Save peterkos/fe4acded03504bca8d87b5f060124378 to your computer and use it in GitHub Desktop.
Adds -=, /=, and *= operation to Strings in Swift.
This file contains hidden or 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
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