Advertisement
oaktree

swift Caesar cipher

May 1st, 2016
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.08 KB | None | 0 0
  1. import Foundation
  2. /*
  3.     Encryption Function:
  4.     Takes a key and mutates any alphabetical character by it.
  5.    
  6.     Note: lines 29 and 32 hopefully can be trimmed
  7. */
  8. func encrypt(key: Int, phrase: String) -> String {
  9.  
  10.     let key = key % 26 // very important to get key within 0-25 range!
  11.     var arr = [Character]() // make an Array ("collection") to store encryped result phrase
  12.  
  13.     for character in phrase.unicodeScalars { // iterate throught each UnicodeScalar in phrase
  14.         if character.value >= 65 && character.value <= 90 { // check if capital Alpha
  15.             // append to arr: get the UnicodeScalar of the current character + key + 7 (for some reason)
  16.             // mod it by 26 to get it within Alpha range, add 65 to get it to ASCII Alpha range
  17.             arr.append(Character(UnicodeScalar(((Int(character.value) + key + 7) % 26) + 65)))         
  18.         } else if character.value >= 97 && character.value <= 122 { // check if lower Alpha
  19.             // see ln25-26; same except for the lower case
  20.             arr.append(Character(UnicodeScalar(((Int(character.value) + key + 7) % 26) + 97)))         
  21.         } else {
  22.             // just append the original if it isn't alphabetical
  23.             arr.append(Character(character))
  24.         }
  25.     }
  26.  
  27.     // return a String composed of the array from ln21
  28.     return String(arr)
  29. }
  30. /*
  31.    
  32.     Decryption Function:
  33.     Simply calls encrypt(...) with a negated key.
  34. */
  35. func decrypt(key: Int, phrase: String) -> String {
  36.     return encrypt(-key, phrase: phrase)
  37. }
  38. /*
  39.     "main()"
  40.     The controller for the program.
  41. */
  42. if Process.arguments.count != 2 {
  43.     // ln 57-60: check for correct number of arguments
  44.     print("\nWrong number of arguments.")
  45.     print("Usuage: caesar <key>")
  46. } else {
  47.     print("Put in the phrase to encrypt: ") // prompt for input, duh
  48.     if let input = readLine() { // will exit if getting a string fails
  49.         if let key = Int(Process.arguments[1]) { // assigns the key, exits if fails
  50.             // ln67-71: presents user with the results
  51.             print("Encrypting...")
  52.             print(encrypt(key, phrase: input))
  53.  
  54.             print("Decrypting...")
  55.             print(decrypt(key, phrase: encrypt(key, phrase: input)))
  56.         } // curly brace
  57.     } // another curly
  58. } // i'm just trolling
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement