App 22 — 24 Apps You Can Make Today

Sort Game

Put items in the right order — tap to swap, detect when the sequence is sorted.

  • ios
↓ Download Playgrounds File

A scrambled sequence of items and a goal: put them in the right order. Tap two items to swap them. The game ends when the sequence is sorted. It's a classic puzzle with surprisingly interesting code.

What you'll build

A row of shuffled items — numbers, colors, or emoji — displayed as tappable cards. Tap one to select it, tap another to swap them. Detect and celebrate when everything is in order.

Key concepts

Shuffled array — Start with a sorted array and shuffle it.

@State var items = [1, 2, 3, 4, 5, 6, 7, 8].shuffled()

Selection and swap — Track which item is selected. On second tap, swap the two.

@State var selectedIndex: Int? = nil

func tap(_ index: Int) {
    if let first = selectedIndex {
        items.swapAt(first, index)
        selectedIndex = nil
    } else {
        selectedIndex = index
    }
}

Win detection — Check whether the array is sorted after every swap.

var isSorted: Bool {
    zip(items, items.dropFirst()).allSatisfy { $0 <= $1 }
}

Highlighting the selected item — Give the selected card a different border or background so the player knows which they've picked.

Algorithms are logic

isSorted above is a tiny algorithm: compare each element to its neighbor; if they're all in order, the sequence is sorted. Writing small algorithms like this — and understanding why they work — is one of the most transferable skills in programming.

Download and run it

Open the Playgrounds file from GitHub, hit Run, and sort.

← All apps in this book