Blog

Functional Snippet #17: Caesar Ciphers

Today we'll have a short and simple snippet. We'll implement the Ceasar cipher in Swift. It is a very simple encryption technique, which shifts every letter in the alphabet by a fixed number of positions. First, we'll write a simple helper function that maps over each scalar, and applies a function to each scalar value:

								func mapScalarValues(s: String, f: (UInt32 )-> UInt32) -> String {
    let scalars = Array(s.unicodeScalars)
    let encrypted = scalars.map { x in
        Character(UnicodeScalar(f(x.value)))
    }
    return String(encrypted)
}

							

Writing a Ceasar cipher is as simple as increasing each scalar value by 7:

								func caesar(plainText: String) -> String {
    return mapScalarValues(plainText) { x in x + 7 }
}

							

Once we have this function, we can also implement a simplified version of ROT-13 which shifts only the capital letters around:

								func rot13(plainText: String) -> String {
    let A: UInt32 = 65
    let Z: UInt32 = 90
    return mapScalarValues(plainText) { x in
        if x >= A && x <= Z  {
            return A + ((x + 13) % 26)
        }
        return x
    }
}

							

For many data structures, map can be a useful operation. We've seen maps on arrays, optionals and now the scalar values of the characters in a string.

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts