How a computer works
You may not believe me when I say it, but a computer is not very smart on its own. The power of computers is all derived from how they’re programmed by people like you and me. If you want to successfully harness the power of a computer — and I assume you do, if you’re reading this book — it’s important to understand how computers work.
It may also surprise you to learn that computers themselves are rather simple machines. At the heart of a computer is a Central Processing Unit (CPU). This is essentially a math machine. It performs addition, subtraction, and other arithmetical operations on numbers. Everything you see when you operate your computer is all built upon a CPU crunching numbers many millions of times per second. Isn’t it amazing what can come from just numbers?
The CPU stores the numbers it acts upon in small memory units called registers. The CPU is able to read numbers into registers from the computer’s main memory,
known as Random Access Memory (RAM). It’s also able to write the number stored in a register back into RAM. This allows the CPU to work with large amounts of data that wouldn’t all fit in the bank of registers.
Here is a diagram of how this works:
As the CPU pulls values from RAM into its registers, it uses those values in its math unit and stores the results back in another register.
Each time the CPU makes an addition, a subtraction, a read from RAM or a write to RAM, it’s executing a single instruction. Each computer program is usually made up of thousands to millions of instructions. A complex computer program such as your operating system, macOS (yes, that’s a computer program too!), may have many millions of instructions in total.
It’s entirely possible to write individual instructions to tell a computer what to do, but for all but the simplest programs, it would be immensely time-consuming and tedious. This is because most computer programs aim to do much more than simple math — computer programs let you surf the Internet, manipulate images, and allow you to chat with your friends.
Instead of writing individual instructions, you write code in a specific programming language, which in your case will be Swift. This code is put through a computer program called a compiler, which converts the code into instructions the CPU knows how to execute. Each line of code you write will turn into many instructions — some lines could end up being tens of instructions!