Type Annotations
Part of the Fundamentals section of Coddy's Swift journey — lesson 5 of 86.
Swift can automatically figure out the type of a value. This is called type inference:
let name = "Alice" // Swift infers this is a String
let age = 25 // Swift infers this is an Int
let price = 9.99 // Swift infers this is a DoubleBut you can also explicitly declare the type using a type annotation. You write a colon after the name, followed by the type:
let name: String = "Alice"
let age: Int = 25
let price: Double = 9.99
let isActive: Bool = trueType annotations are useful when:
- You want to be extra clear about what type a value is
- You declare a variable without an initial value
var score: Int // Declared but not yet assigned
score = 100 // Assigned laterWithout the type annotation, Swift wouldn't know what type score should be.
Challenge
BeginnerCreate four constants with explicit type annotations:
nameof typeStringwith value"Alice"ageof typeIntwith value30priceof typeDoublewith value9.99isOnlineof typeBoolwith valuetrue
Print all four values on separate lines.
Cheat sheet
Swift can automatically determine the type of a value through type inference:
let name = "Alice" // Swift infers String
let age = 25 // Swift infers Int
let price = 9.99 // Swift infers DoubleYou can explicitly declare types using type annotations with a colon after the variable name:
let name: String = "Alice"
let age: Int = 25
let price: Double = 9.99
let isActive: Bool = trueType annotations are useful when declaring a variable without an initial value:
var score: Int // Declared but not assigned
score = 100 // Assigned laterTry it yourself
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