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
implementationWe introduce the rot13
func
. This method receives a String
and returns a String
. It begins by creating an empty Character array.
string
's data. We cast these values to Ints.UnicodeScalar
and shift letters 13 places depending on their values.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?
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.
short
reviewA 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.