Ad space (banner)
๐ŸฆSwift Lessons
Lesson 34 / 68

Building a Caesar Cipher (a Character-Shifting Cipher)

In this lesson you will learn how to implement a Caesar cipher in Swift, and understand the basic idea of encrypting by shifting characters. This is for anyone searching for "Swift Caesar cipher implementation".

The Caesar cipher is a simple cipher from ancient Rome that replaces each letter with the one a fixed number of positions further along the alphabet. It is the same idea as a childhood game of shifting every letter by three.

The sample code converts characters to Unicode scalar values with text.unicodeScalars and, checking whether each is in the alphabet, computes the shifted letter with (c.value - 65 + UInt32(shift)) % 26 + 65. Notice how anything that is not a letter is passed through unchanged.

A common stumbling block for beginners is the character-code arithmetic. You need % 26 to handle the case where the shifted result runs past the end of the alphabet (A to Z).

It is very simple next to modern cryptography, but it is an ideal exercise for practising character-code arithmetic.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)