Home
Swift
Caesar Cipher
Updated Aug 23, 2023
Dot Net Perls
Caesar cipher. In a Caesar cipher, all letters are shifted by a certain number of places. Then the characters are wrapped to fit within the alphabetical range.
In Swift 5.8, we can loop over integer values in a string with utf8. And with UnicodeScalar we can shift those characters into the desired range.
Example implementation. This code introduces the caesar() method. It accepts a String and a "shift" Int. And it returns a String.
Start We create an empty Character array. This is where we append() our shifted chars as we compute them.
Next We use an if-statement to test whether the value exceeds a lowercase "z." If so we shift it backwards.
if
Tip We use the UnicodeScalar type to convert an integer value (based on an arithmetic expression) back into a Character.
Convert Int, Character
Finally We return a new string based on the characters we added in the Character array. This is the result of caesar().
func caesar(value: String, shift: Int) -> String { // Empty character array. var result = [Character]() // Loop over utf8 values. for u in value.utf8 { // Apply shift to UInt8. let s = Int(u) + shift // See if value exceeds Z. // ... The Z is 26 past "A" which is 97. // ... If greater than "Z," shift backwards 26. // ... If less than "A," shift forward 26. if s > 97 + 25 { result.append(Character(UnicodeScalar(s - 26)!)) } else if s < 97 { result.append(Character(UnicodeScalar(s + 26)!)) } else { result.append(Character(UnicodeScalar(s)!)) } } // Return String from array. return String(result) } // Test Caesar cipher on this string. let value1 = "test" print(value1) let value2 = caesar(value: value1, shift: 18) let value3 = caesar(value: value2, shift: -18) print("\(value2) \(value3)") let value4 = caesar(value: value1, shift: 1) let value5 = caesar(value: value4, shift: -1) print("\(value4) \(value5)") let value6 = "exxegoexsrgi" let value7 = caesar(value: value6, shift: -4) print("\(value6) \(value7)")
test lwkl test uftu test exxegoexsrgi attackatonce
Some notes. A Caesar cipher is a more general form of the ROT13 algorithm. In it we rotate characters any number of places, not just 13 places as in ROT13. These ciphers have limited use.
A review. The Caesar cipher is not a good form of encryption. It only obfuscates text. But it can help us learn how to manipulate characters with their underlying integral values.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen