Numbers
Part of the Fundamentals section of Coddy's Swift journey — lesson 6 of 86.
Variables are containers that hold data values. They are used to store, manipulate, and display information within a program.
In short, a variable is like a memory unit that we can access by typing the name of the variable.
Each variable has a unique name and a value that can be of different types. Swift is a type-safe language, meaning it's strict about the types of values your variables can hold.
To initialize a variable or constant, we use the following format:
let constantName = value
var variableName = valueLet's take a look at the different types of numbers:
Int — an integer (whole number), such as 1 or -2.
Double — a floating-point number (decimal), such as 1.32 or 0.98.
For example:
To initialize a constant of type Int with the name a and the value 3:
let a = 3To initialize a constant of type Double with the name b and the value 13.2:
let b = 13.2Note: Variable names cannot start with a number. Use camelCase to separate words (e.g., playerName), not spaces or hyphens.
Challenge
BeginnerWrite code that initializes a constant named myVar with the value 5.
- Replace the
?with the correct value - Lines starting with
//are comments — they explain what to do but don't affect your code - Only change the line that says
let myVar = ?
Cheat sheet
Variables are containers that hold data values. Use let for constants and var for variables:
let constantName = value
var variableName = valueSwift has different numeric types:
Int — whole numbers like 1 or -2
Double — decimal numbers like 1.32 or 0.98
Examples:
let a = 3 // Int
let b = 13.2 // DoubleNote: Variable names cannot start with a number. Use camelCase for multi-word names (e.g., playerName).
Try it yourself
// Type your code below
let myVar = ?
// Don't change the line below
print("myVar = \(myVar)")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input