Last active
April 6, 2019 11:15
-
-
Save luki/70302cf038a98ba94352efcf9fc96d87 to your computer and use it in GitHub Desktop.
Caesar Encryption (Functional/Recursive Solution in Swift)
This file contains 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
// 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