Expressions, Variables & Constants

Swift Chapter 3 of the Ultimate Swift Series 25 min read April 10, 2026 Beginner

In This Article

  1. How Computers Actually Think
  2. Number Systems: Binary and Hexadecimal
  3. From Code to CPU: How Swift Gets Executed
  4. Code Comments: Notes for Humans
  5. Arithmetic in Swift
  6. Built-in Math Functions
  7. Constants: Data That Doesn't Change
  8. Variables: Data That Does
  9. Naming Your Data Well
  10. Compound Assignment Operators
  11. Exercises
  12. 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:

// Decimal: each position is a power of 10 (4 × 100) + (2 × 10) + (3 × 1) = 423

In binary, each position is a power of 2. The binary number 1101 breaks down as:

// Binary: each position is a power of 2 (1 × 8) + (1 × 4) + (0 × 2) + (1 × 1) = 13

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:

// Hex digit → 4 binary digits // f = 1111, a = 1010, c = 1100, e = 1110 // hex "face" = 1111 1010 1100 1110 = 64206 decimal

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.

You don't need to memorize this

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.

// This is a single-line comment /* This is a multi-line comment. It can span as many lines as you need. Great for explaining complex logic. */ /* Swift supports nested comments /* like this inner comment */ which is unusual — most languages don't allow this */

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:

print("Hello from Swift!") // Output: Hello from Swift!

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

2 + 6 // 8 (addition) 10 - 2 // 8 (subtraction) 2 * 4 // 8 (multiplication) 24 / 3 // 8 (division)

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.

Watch your whitespace

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:

22 / 7 // 3 — not 3.14! Integer division rounds down 22.0 / 7.0 // 3.142857... — decimal division works correctly

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:

28 % 10 // 8 (10 goes into 28 twice, remainder 8) 15 % 4 // 3 (4 goes into 15 three times, remainder 3) 16 % 2 // 0 (even number — no remainder)

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:

1 << 3 // 8 (shift left 3 = multiply by 2³ = 8) 32 >> 2 // 8 (shift right 2 = divide by 2² = 8)

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:

350 / 5 + 2 // 72 (division first, then addition) 350 / (5 + 2) // 50 (parentheses force addition first)

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:

sin(45 * Double.pi / 180) // 0.7071... (sine of 45°) cos(135 * Double.pi / 180) // -0.7071... (cosine of 135°) (2.0).squareRoot() // 1.4142... (square root of 2) max(5, 10) // 10 min(-5, -10) // -10 // You can combine them: max((2.0).squareRoot(), Double.pi / 2) // 1.5707...

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.

let numberOfPlanets: Int = 8 let pi: Double = 3.14159 let greeting: String = "Hello, Swift!"

Breaking this down:

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:

let number: Int = 10 number = 0 // ERROR: Cannot assign to value: 'number' is a 'let' constant

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 vs. Double vs. Float

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:

var score: Int = 0 score = 10 // Now score is 10 score = 25 // Now score is 25 var balance: Double = 1000.00 balance = 950.50 // Withdrew some money

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.

Default to let

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:

var population: Int = 1_000_000 // Same as 1000000, but easier to read let distanceToMoon: Double = 384_400.0 // Kilometers

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

// Good — you know exactly what these hold let playerAge: Int = 28 let maxLoginAttempts: Int = 3 var currentTemperature: Double = 72.5 // Bad — what do these mean? let a: Int = 28 let x: Int = 3 var temp: Double = 72.5

Swift naming conventions

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:

var counter: Int = 0 counter += 1 // counter is now 1 (same as: counter = counter + 1) counter -= 1 // counter is now 0 (same as: counter = counter - 1) counter = 10 counter *= 3 // counter is now 30 (same as: counter = counter * 3) counter /= 2 // counter is now 15 (same as: counter = counter / 2)

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

  1. Declare a constant called myAge of type Int and set it to your age.
  2. Declare a variable called averageAge of type Double. Set it to your age, then change it to the average of your age and 30.
  3. Create a constant testNumber set to any integer. Create another constant evenOdd set to testNumber % 2. Try different values for testNumber — what pattern do you see?
  4. Create a variable answer starting at 0. Increment by 1, add 10, multiply by 10, then shift right by 3. What's the final value?
  5. Declare constants rating1, rating2, rating3 as Double values. Calculate their average and store it in averageRating.
  6. Bonus: Declare voltage and current as Double constants. Calculate power (voltage × current) and resistance (power ÷ current²).

Key Points

What You Learned

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