Variables and Types in Swift
Learn about variables, constants, type inference, and optionals in Swift with practical Docker-ready examples
Swift’s type system is one of its defining features: static and strong, yet flexible enough that you rarely need to write types explicitly. The compiler infers types from context, catches mismatches at compile time, and introduces optionals to handle the absence of a value safely — eliminating an entire class of null pointer crashes.
As a multi-paradigm language, Swift treats both value types (structs, enums) and reference types (classes) as first-class citizens. This tutorial focuses on the foundational building blocks: declaring variables and constants, working with Swift’s core types, converting between them, and understanding optionals.
Variables and Constants
Swift draws a sharp distinction between mutable variables (var) and immutable constants (let). Prefer let by default; the compiler will tell you when you actually need var.
Create a file named variables.swift:
| |
Swift’s type inference is pervasive: let language = "Swift" is equivalent to let language: String = "Swift". You only need explicit annotations when the inferred type isn’t what you want (e.g., let x: Float = 3.14 instead of the default Double).
Core Types and Type Safety
Swift’s type system is strict: you cannot mix types without explicit conversion. This prevents subtle bugs that plague loosely-typed languages.
Create a file named variables_types.swift:
| |
Notice that Swift will not implicitly widen Int to Double — Double(widthInt) must be written explicitly. This verbosity is intentional: it makes type conversions visible and prevents accidental precision loss.
Optionals: Safe Nil Handling
Swift’s answer to null pointer exceptions is the optional type. An optional String? is either a String or nothing at all — and the compiler forces you to handle both cases before using the value.
Create a file named variables_optionals.swift:
| |
Optionals appear throughout Swift APIs — any value that might be absent is an optional. The ?? nil coalescing operator and ?. optional chaining operators let you work with optionals concisely without force-unwrapping (!), which should be avoided unless you are certain the optional contains a value.
Running with Docker
| |
Expected Output
Running variables.swift:
Language: Swift
Version: 6.0
Open source: true
First released: 2014
Downloads: 1000000
Current year: 2024
Total downloads: 1500000
Diameter: 10.0
Running variables_types.swift:
Scaled width: 2880.0
Hello, Swift!
Total: 34.93
Debug mode: false, Verbose: true
value is an Int
Running variables_optionals.swift:
Username before login: not set
Welcome back, swiftcoder!
Hello, swiftcoder
No user provided
Score: 1500
Username length: 10
swiftcoder has 1500 points
Title: Swift Tutorial
Key Concepts
letvsvar: Useletfor constants (the default); usevaronly when the value needs to change. The compiler enforces this distinction.- Type inference: Swift deduces types from the assigned value — explicit annotations are optional but can be useful for clarity or to override the default (e.g.,
Floatinstead ofDouble). - No implicit conversions: Swift never silently widens or narrows numeric types. You must write
Double(myInt)explicitly, which keeps type boundaries visible in code. Stringis a value type: Unlike Java or C#, SwiftStringis a struct that copies on assignment, not a heap-allocated object — which makes its behavior predictable and thread-safe.- Optionals (
T?): The type system itself encodes the presence or absence of a value. AString?and aStringare distinct types — you cannot use one where the other is expected. - Optional binding (
if let,guard let): The idiomatic way to unwrap optionals safely. Avoid force unwrapping (!) in production code. - Nil coalescing (
??): Provides a default value inline when an optional is nil, reducing boilerplate compared to explicitif/elsechecks. AnyandAnyObject: Swift provides escape hatches for dynamic typing, but strongly prefers generics and protocols for type-safe polymorphism.
Comments
Loading comments...
Leave a Comment