Skip to content

Instantly share code, notes, and snippets.

@dustinsenos
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinsenos/e3953870ca3589e355a3 to your computer and use it in GitHub Desktop.
Save dustinsenos/e3953870ca3589e355a3 to your computer and use it in GitHub Desktop.
ROT13 in Swift with Emoji support 😍
//: Playground - noun: a place where people can play
// Converts a string into it's ROT13 equavalent. Note, this is not a secure way (at all) to encrypt private data.
// Please look into BCRYPT or something similar for sensistive data
extension String {
var encrypt: String {
return self.run(self, rotateAmount: 13)
}
var decrypt: String {
return self.run(self, rotateAmount: -13)
}
func run(str:String, rotateAmount:Int) -> String {
return "".join(str.characters.map {
(char) -> String in
let num = String(char).unicodeScalars
let characterIntVal = num.first!.value
let rotatedIntVal = Int(characterIntVal) + rotateAmount
let newStringValue = String(UnicodeScalar(rotatedIntVal))
return newStringValue
}
)
}
}
let str = "Woot! Orange cats are the best 😍. If you like cats, that is."
"Encrypted:"
let encrypted = str.encrypt
"Decrypted:"
let decrpyed = encrypted.decrypt
@kocodude
Copy link

i believe the lowest int value will be 'a' which is 65 if i remember correctly. This seems great, but I'm wondering about characters with Int values less than the rotated amount.

@dustinsenos
Copy link
Author

@kocodude I move things ahead by 13 now (rather than backwards, that was a typo in the last rev), so unless you’re at the very last character in unicode, you should always have room to move forward.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment