App 20 — 24 Apps You Can Make Today

Not-so-Secret Messages

Encode and decode messages with a simple cipher — string manipulation with map() and character operations.

  • ios
↓ Download Playgrounds File

A secret message app that scrambles your text using a simple cipher. Type your message, watch it transform, and decode it back. The real star of the show is how surprisingly little code it takes to transform every character in a string.

What you'll build

Two text areas: one for your original message, one for the encoded version. Type in either field and the other updates. The encoding could be a Caesar cipher (shift letters by N), ROT13, or something you invent.

Key concepts

map() over a string's characters — A String is a collection of Character values. You can .map() over it just like an array.

func encode(_ text: String, shift: Int = 3) -> String {
    String(text.map { char in
        guard let ascii = char.asciiValue else { return char }
        if char.isLetter {
            let base = char.isUppercase ? 65 : 97
            let shifted = (Int(ascii) - base + shift) % 26 + base
            return Character(UnicodeScalar(shifted)!)
        }
        return char
    })
}

Character and UnicodeScalar — Swift's Character type handles the full Unicode range. For simple ciphers, working with ASCII values (char.asciiValue) makes the math straightforward.

Two-way binding — Wire both text fields to state and update the encoded/decoded version using onChange.

.onChange(of: plainText) {
    encodedText = encode(plainText)
}

Functional transformation

map() transforms each element of a collection into something new, without a for loop. encode() above reads as: "for every character, return the shifted version." Once you're comfortable with map(), filter(), and reduce(), a huge amount of code gets shorter and clearer.

Download and run it

Open the Playgrounds file from GitHub, hit Run, and keep secrets.

← All apps in this book