In This Article
- How Computers Actually Think
- Number Systems: Binary and Hexadecimal
- From Code to CPU: How Swift Gets Executed
- Code Comments: Notes for Humans
- Arithmetic in Swift
- Built-in Math Functions
- Constants: Data That Doesn't Change
- Variables: Data That Does
- Naming Your Data Well
- Compound Assignment Operators
- Exercises
- Key Points
Before you can build apps, you need to understand how computers handle data at the most fundamental level. This chapter covers the building blocks: how machines process numbers, how you perform calculations in Swift, and how you store and name data using constants and variables.
Open a new Playground in Xcode and follow along. Every code example in this chapter is designed to run in a playground.
How Computers Actually Think
A computer is, at its core, a math machine. The brain of the computer is the Central Processing Unit (CPU). It does one thing extremely well: perform arithmetic operations on numbers, millions of times per second.
The CPU works with small memory slots called registers. When it needs data, it pulls numbers from the computer's main memory (RAM) into registers, runs calculations, and writes results back. That's the entire cycle. Every app you've ever used — from Safari to Instagram — is built on this simple loop of reading, calculating, and writing numbers.
Everything on your screen is a number. Text? Each character maps to a number (the letter "A" is 65). Images? Each pixel is three numbers: how much red, green, and blue. Sound? A sequence of numbers representing air pressure over time. The CPU doesn't know what any of it means — it just does the math.
Number Systems: Binary and Hexadecimal
Why computers use binary
You count in base 10 (decimal) because you have ten fingers. Computers count in base 2 (binary) because, at the hardware level, a circuit is either on or off. Voltage present = 1. No voltage = 0. That's it — two states, two digits.
In decimal, the number 423 breaks down by powers of 10:
In binary, each position is a power of 2. The binary number 1101 breaks down as:
Each binary digit is called a bit. Eight bits make a byte. A 64-bit CPU — which is what every modern Mac and iPhone has — can process numbers up to 18.4 quintillion in a single operation.
Hexadecimal: a shorthand for binary
Binary numbers get long fast. The number 255 in binary is 11111111. Writing 32-bit or 64-bit numbers in binary is impractical, so programmers use hexadecimal (base 16) as a compact shorthand.
Hex uses digits 0-9 plus letters a-f (where a=10, b=11, c=12, d=13, e=14, f=15). Each hex digit maps to exactly four binary digits, making conversion trivial:
You'll encounter hex in Swift when working with colors (0xFF0000 for red) and memory addresses. The largest 32-bit number? In decimal it's 4,294,967,295. In hex it's just ffffffff.
Understanding binary and hex helps you appreciate what happens under the hood, but you won't manually convert numbers in everyday Swift programming. The compiler handles all of that. Think of this as background knowledge that makes you a better developer.
From Code to CPU: How Swift Gets Executed
Writing individual CPU instructions by hand would be impossibly tedious. Instead, you write source code in Swift, and a program called the compiler translates it into the tiny machine instructions the CPU understands.
A single line of Swift might become dozens of machine instructions. The compiler also catches mistakes before your code runs — type mismatches, missing values, syntax errors. This is why Swift is called a compiled language, and it's one of the reasons Swift code runs so fast.
Think of coding like writing a recipe. You specify the ingredients (data) and the steps (operations). The compiler is the translator that turns your human-readable recipe into something the CPU can execute.
Code Comments: Notes for Humans
Comments are text in your code that the compiler completely ignores. They exist for one reason: to help humans (including future you) understand what the code does and why.
Use comments to explain why you wrote something a certain way, not what the code does (the code itself should be clear enough for that). And don't over-comment — if every line needs an explanation, the code itself probably needs to be clearer.
Printing output
To see what your code is doing, use print(). It sends text to the debug console at the bottom of the playground:
You'll use print() constantly while learning. It's the simplest way to verify that your code is doing what you expect.
Arithmetic in Swift
Swift supports the arithmetic operations you already know, plus a few you might not. Each operation uses a symbol called an operator.
The basic four
Each line is an expression — a piece of code that produces a value. The result appears in the playground's results sidebar on the right.
Operators must have whitespace on both sides or no whitespace. 2 + 6 and 2+6 work. But 2 +6 and 2+ 6 will cause compiler errors. Stick with spaces on both sides — it's easier to read.
Integer vs. decimal division
Here's something that catches every beginner:
When both numbers are integers, Swift produces an integer result (rounded down). To get a decimal result, use decimal numbers (with a .0).
The remainder operator
The % operator gives you the remainder after division. It's incredibly useful and shows up everywhere in programming:
A common use: checking if a number is even or odd. If number % 2 equals 0, it's even. If it equals 1, it's odd.
Shift operators
Shift operators move binary digits left or right. They're specialized, but worth knowing:
Shifting left by n is the same as multiplying by 2n. Shifting right by n is dividing by 2n. In the old days, programmers used shifts because they were faster than multiplication. Modern compilers handle this optimization for you, so shifts are mainly used for binary data manipulation now.
Order of operations
Swift follows the same mathematical precedence you learned in school: multiplication and division happen before addition and subtraction. Use parentheses to make your intent explicit:
Even when parentheses aren't strictly necessary, adding them makes your code clearer. Future you will be grateful.
Built-in Math Functions
Swift and the system libraries give you a rich set of math functions:
Double.pi is a constant that Swift provides — pi to the maximum precision the computer supports. You'll use these functions when building games (trigonometry for movement), graphics (calculating positions), and data processing (statistics).
Constants: Data That Doesn't Change
Now we get to the most important concept in this chapter: giving names to data. A constant stores a value that never changes after you set it.
Breaking this down:
let— declares a constant (the value cannot change)numberOfPlanets— the name you choose for this data: Int— the type annotation, telling Swift this holds an integer= 8— the value you're assigning
The = sign is the assignment operator. It doesn't mean "equals" in the math sense — it means "store this value in this name."
If you try to change a constant after declaring it:
The compiler stops you. This is deliberate — constants prevent accidental changes to data that should stay fixed. The number of seats on an airplane, the value of pi, a user's birth year — these are things that don't change.
Int stores whole numbers. Double stores decimals with high precision (about 15 significant digits). Float stores decimals with lower precision (about 7 digits) but uses less memory. In practice, use Double for decimal numbers unless you have a specific reason not to.
Variables: Data That Does Change
When you need data that can change, use var instead of let:
You can reassign a variable as many times as you want, but the type must stay the same. A variable declared as Int can't suddenly hold a String.
Always start with let. Only switch to var when you know the value needs to change. Xcode will even warn you if you declare a var but never modify it. Using constants wherever possible makes your code safer and easier to reason about.
Swift also lets you use underscores to make large numbers readable:
Naming Your Data Well
Names are more important than you think. A well-named variable is documentation. A poorly-named one is a puzzle.
Good names are specific
Swift naming conventions
- Use camelCase: start lowercase, capitalize each new word —
numberOfItems,isLoggedIn - Keep abbreviations consistent —
sourceURL(all caps) orurlDescription(all lowercase) - Name booleans as questions —
isVisible,hasAccess,canEdit
You'll read your own code far more often than you write it. Invest the extra few seconds to choose a clear name.
Compound Assignment Operators
Incrementing and decrementing variables is so common that Swift has shorthand operators for it:
These compound assignment operators (+=, -=, *=, /=) read the current value, perform the operation, and assign the result back — all in one step. You'll use += and -= constantly.
Exercises
Try These in Your Playground
- Declare a constant called
myAgeof typeIntand set it to your age. - Declare a variable called
averageAgeof typeDouble. Set it to your age, then change it to the average of your age and 30. - Create a constant
testNumberset to any integer. Create another constantevenOddset totestNumber % 2. Try different values fortestNumber— what pattern do you see? - Create a variable
answerstarting at 0. Increment by 1, add 10, multiply by 10, then shift right by 3. What's the final value? - Declare constants
rating1,rating2,rating3asDoublevalues. Calculate their average and store it inaverageRating. - Bonus: Declare
voltageandcurrentasDoubleconstants. Calculatepower(voltage × current) andresistance(power ÷ current²).
Key Points
What You Learned
- Computers are math machines — everything reduces to arithmetic on numbers
- Binary (base 2) is how computers store data; hexadecimal (base 16) is a compact shorthand
- The Swift compiler converts your source code into CPU instructions
- Comments (
//and/* */) document your code for humans print()outputs text to the console for debugging- Arithmetic operators:
+-*/%<<>> - Integer division rounds down — use
.0for decimal results letdeclares constants (immutable);vardeclares variables (mutable)- Default to
letand only usevarwhen the value must change - Use descriptive camelCase names:
playerScorenotps - Compound operators:
+=-=*=/=modify and reassign in one step
In the next chapter, we'll explore Types & Operations — how Swift's type system works, type conversion, type inference, and the String type for working with text.
See these concepts in action
Our Swift Fundamentals video course covers all of this with 96 video lessons. Watch the first 10 free.
Watch Swift Videos