Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Created July 23, 2016 14:58
Show Gist options
  • Save pauljohanneskraft/31ac46e3a507164e9cfbf4ba5718a12a to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/31ac46e3a507164e9cfbf4ba5718a12a to your computer and use it in GitHub Desktop.
enables fast switching between certain letters in Strings

String Replacer

enables fast switching between certain letters in Strings

var s = StringReplacer(("E", "3"), ("g", "9"), ("O", "0"), ("o", "0"), ("l", "1"))

s["1"] = "l"

var str = "hallo"

s.replace(in: &str)
print(str) // Prints "ha110"
s.replace(in: &str)
print(str) // Prints "hall0"
struct StringReplacer {
typealias Element = (key: Character, value: Character)
var replacements = [Character : Character]()
init() {}
init(_ values: Element...) {
for v in values {
replacements[v.key] = v.value
}
}
subscript(str: Character) -> Character? {
get { return replacements[str] }
set { replacements[str] = newValue }
}
func replace(in str: inout String) {
for i in str.characters.indices {
let c = str.characters[i]
if let r = self.replacements[c] {
str.replaceSubrange(i...i, with: "\(r)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment