Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Created August 3, 2024 14:09
Show Gist options
  • Save dedeexe/74235a96e6acff09d35f5070f91b286e to your computer and use it in GitHub Desktop.
Save dedeexe/74235a96e6acff09d35f5070f91b286e to your computer and use it in GitHub Desktop.
A simple example of Caesar Cipher made in swift
struct CaesarCipher {
enum Operation {
case encode
case decode
}
let charTable: [Character]
private func crypt(text: String, shift: Int, operation: Operation) -> String {
var result: [Character] = []
let charTable = operation == .decode ? Array(charTable.reversed()) : charTable
for character in text {
guard let index = charTable.firstIndex(of: character) else {
result.append(character)
continue
}
let newIndex = (index + shift) % charTable.count
result.append(charTable[newIndex])
}
return String(result)
}
func callAsFunction(text: String, shift: Int, operation: Operation) -> String {
crypt(text: text, shift: shift, operation: operation)
}
}
// ===================================
// USAGE
// ===================================
let charTable = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890 ,."
let cipher = CaesarCipher(charTable: Array(charTable))
let sourceText = "Yes, this is my source text."
let shift = 234
let encodedText = cipher(text: sourceText, shift: shift, operation: .encode)
let decodedText = cipher(text: encodedText, shift: shift, operation: .decode)
print("===== RESULT =====")
print("Source Text: \(sourceText)")
print("Encode Text: \(encodedText)")
print("Decode Text: \(decodedText)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment