Skip to content

Instantly share code, notes, and snippets.

@luki
Last active April 6, 2019 11:15
Show Gist options
  • Save luki/70302cf038a98ba94352efcf9fc96d87 to your computer and use it in GitHub Desktop.
Save luki/70302cf038a98ba94352efcf9fc96d87 to your computer and use it in GitHub Desktop.
Caesar Encryption (Functional/Recursive Solution in Swift)
// For uppercase letters
func encrypt(key: Int) -> ((String) -> String) {
// 25 is the highest number for a possible shift
let actualKey = key % 25
// If the new index is bigger than 90 (which is an X), calculate the remainder and add 64 (which is A)
var actualNewIndex: (Int) -> Int = { i in
if i > 90 { return i % 90 + 64 }
return i
}
return { str in
// Return an empty string if empty
if (str.isEmpty) { return String() }
return String(format: "%c", actualNewIndex(str.first!.unicodeScalars.first!.hashValue + actualKey)) + encrypt(key: key)(String(str.dropFirst()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment