Home
Map
ROT13 FuncImplement the ROT13 cipher with a func. Loop over and convert characters.
Swift
This page was last reviewed on Aug 23, 2023.
ROT13. The ROT13 algorithm obscures text by changing the letters in words to be shifted 13 places forward or backward. It is not encryption.
In Swift 5.8, we implement ROT13 in a func. We use the UnicodeScalar type to manipulate Characters by their numeric codes. We create a rotated string.
Func implementation. We introduce the rot13 func. This method receives a String and returns a String. It begins by creating an empty Character array.
Info We use some ASCII constants for letters. There values correspond to uppercase and lowercase letters in ASCII.
Note Utf8 accesses and returns the ASCII numeric values from the string's data. We cast these values to Ints.
Convert Int, Character
Then We test the character values with if and else. We use UnicodeScalar and shift letters 13 places depending on their values.
Return We return a string based on the values appended to our Character array. We test rot13 in the rest of the program.
func rot13(value: String) -> String { // Empty character array. var result = [Character]() // Some ASCII constants. // A = 65 // M = 77 // Z = 90 // a = 97 // m = 109 // z = 122 let upperA = 65 let upperM = 77 let upperZ = 90 let lowerA = 97 let lowerM = 109 let lowerZ = 122 // Loop over utf8 values in string. for u in value.utf8 { let s = Int(u) var resultCharacter = Character(UnicodeScalar(s)!) if s >= lowerA && s <= lowerZ { if s >= lowerM { resultCharacter = Character(UnicodeScalar(s - 13)!) } else { resultCharacter = Character(UnicodeScalar(s + 13)!) } } else if s >= upperA && s <= upperZ { if s >= upperM { resultCharacter = Character(UnicodeScalar(s - 13)!) } else { resultCharacter = Character(UnicodeScalar(s + 13)!) } } // Append to Character array. result.append(resultCharacter) } // Return String. return String(result) } // Test the method. let input = "Do you have any cat pictures?" let result = rot13(value: input) let roundTrip = rot13(value: result) print(input) print(result) print(roundTrip)
Do you have any cat pictures? Qb lbh unir nal png cvpgherf? Do you have any cat pictures?
Some notes. ROT13 is a terrible way to encrypt text. But this example helps us learn a programming language. We must access UnicodeScalars and manipulate character values in Swift.
A short review. A trick to manipulating strings in Swift is the use of UnicodeScalar. With this type we can shift characters based on their numeric values. The utf8 property also helps.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.