Skip to content

Instantly share code, notes, and snippets.

@ktustanowski
Last active August 6, 2017 12:19
Show Gist options
  • Save ktustanowski/b8879f6ff1df2b2dbe67039a85805b07 to your computer and use it in GitHub Desktop.
Save ktustanowski/b8879f6ff1df2b2dbe67039a85805b07 to your computer and use it in GitHub Desktop.
class NumbersDecryptor: Decryptor {
fileprivate var cipherDictionary = [String : String]()
override func decrypt(_ input: String) -> String? {
cipherDictionary.removeAll()
// The most annoying part of this is to properly replace characters in message
// so when we do .separatedBy we just get strings we can change to numbers.
// This may break depending on what text you will use and whether you are using characters
// that are currently supported or not. I even noticed that – is not the same as -.
let numbers = input.replacingOccurrences(of: " ", with: "-")
.replacingOccurrences(of: ":", with: "")
.replacingOccurrences(of: "\"", with: "")
.replacingOccurrences(of: ",", with: "")
.replacingOccurrences(of: "`", with: "")
.replacingOccurrences(of: ".", with: "")
.replacingOccurrences(of: "'", with: "-")
.replacingOccurrences(of: "?", with: "")
.replacingOccurrences(of: "!", with: "")
.replacingOccurrences(of: "'", with: "-")
.replacingOccurrences(of: "–", with: "-")
.replacingOccurrences(of: "“", with: "")
.replacingOccurrences(of: "”", with: "")
.components(separatedBy: "-")
for number in numbers {
guard Int(number) != nil else {
assertionFailure("Unsupported character found in _\(number)_. Please remove it or add another .replacingOccurrences(of:")
break }
guard cipherDictionary[number] == nil else { continue }
cipherDictionary[number] = substitute(number)
}
var output = input
let allNumbers = cipherDictionary.keys.sorted { Int($0)! > Int($1)! }
for number in allNumbers {
guard let text = cipherDictionary[number] else { continue }
output = output.replacingOccurrences(of: number, with: text)
}
return output.replacingOccurrences(of: "-", with: "")
.replacingOccurrences(of: "–", with: "")
}
override func substitute(_ string: String) -> String {
guard let index = Int(string),
index > 0, index < alphabet.count else { return "?" }
return alphabet[index - 1].isEmpty ? string : alphabet[index - 1]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment