Swift Basics
This guide introduces fundamental Swift concepts, focusing on data types, variables, constants, and basic syntax.
Fundamental Data Types
Swift provides several core data types:
- Int: Whole numbers (e.g.,
100,-50) - Double: 64-bit floating-point numbers (e.g.,
2.71828) - Float: 32-bit floating-point numbers
- Bool:
trueorfalsevalues - String: Text (e.g.,
"Welcome") - Collections:
Array,Set,Dictionary
Note: Prefer Double for floating-point numbers unless Float is needed for specific cases (e.g., memory constraints). Use Int for general integer purposes.
Constants and Variables
- Constants (
let): Immutable values. - Variables (
var): Mutable values.
let maxScore = 100 // Constant
var currentScore = 0 // Variable- Declare multiple variables/constants in one line:
var a = 1.0, b = 2.0, c = 3.0- Initialize constants later, ensuring a value before use:
var mode = "test"
let maxPlayers: Int
if mode == "test" {
maxPlayers = 50
} else {
maxPlayers = 10
}Type Annotations
Explicitly declare types using a colon (:):
var greeting: String = "Welcome"
var height, width, depth: DoubleSwift infers types from initial values, reducing the need for annotations:
let answer = 42 // Inferred as Int
let euler = 2.71828 // Inferred as DoubleNaming Rules
- Names can include Unicode characters:
let Σ = 1.414 // Square root of 2
let こんにちは = "Hello, world"
let 🦁 = "lion"- Cannot start with numbers, or include whitespace, mathematical symbols, or specific Unicode characters.
- Cannot redeclare names or convert constants to variables.
Printing Values
Use print() with string interpolation:
var userGreeting = "Welcome!"
print("Current greeting: \(userGreeting)")
// Prints: Current greeting: Welcome!Comments
- Single-line:
// Single-line comment - Multi-line:
/* Multi-line comment */ - Nested multi-line comments:
/* Main comment
/* Nested comment */
End of main comment */Semicolons
Semicolons (;) are optional unless multiple statements are on one line:
let emoji = "😺"; print(emoji) // Prints 😺Integers
- Signed:
Int8,Int16,Int32,Int64(e.g.,Int8:-128to127) - Unsigned:
UInt8,UInt16,UInt32,UInt64(e.g.,UInt8:0to255) - Use
Intfor general use, matching platform word size. - Check bounds:
let min = UInt8.min // 0
let max = UInt8.max // 255Numeric Literals
Integers:
- Decimal:
25 - Binary:
0b11001(25) - Octal:
0o31(25) - Hexadecimal:
0x19(25)
Floating-point:
- Decimal:
15.625,1.5625e1(1.5625 × 10¹) - Hexadecimal:
0xF.Ap0(15.625) - Use underscores for readability:
let largeNumber = 1_000_000
let preciseDouble = 123_456.789_012Type Safety and Inference
Swift is type-safe, preventing type mismatches. Type inference deduces types:
let constant = 2.71828 // Inferred as Double
let result = 2 + 0.71828 // Inferred as DoubleType Conversion
Explicit conversion is required:
let thousand: UInt16 = 1_000
let ten: UInt8 = 10
let total = thousand + UInt16(ten) // 1010For floating-point and integers:
let whole = 5
let fraction = 0.859
let sum = Double(whole) + fraction // 5.859
let intSum = Int(sum) // 5 (truncates)Type Aliases
Define alternative type names:
typealias PixelValue = UInt8
var brightness = PixelValue.max // 255Booleans
Bool is true or false:
let isSunny = true
if isSunny {
print("It's a sunny day!")
} else {
print("It's cloudy.")
}
// Prints: It's a sunny day!Tuples
Group values into a single compound value:
let userStatus = (200, "Online") // Type: (Int, String)Access elements:
- By index:
userStatus.0(200) - By name:
let response = (code: 200, message: "Success") - Decompose:
let (code, message) = userStatus
Optionals
Handle absent values with nil:
let input = "456"
let number: Int? = Int(input) // Optional Int- Check for
nil:
if number != nil {
print("Valid number")
}- Optional Binding:
if let value = number {
print("Value is \(value)") // Value is 456
}- Nil-Coalescing Operator (
??):
let username: String? = nil
let displayName = username ?? "Guest"
print("Hello, \(displayName)!") // Hello, Guest!- Force Unwrapping (
!): Use only if guaranteed non-nil:
let value = number! // 456- Implicitly Unwrapped Optionals (
Type!):
let assumedName: String! = "User"
let name: String = assumedName // No unwrapping neededMemory Safety
Swift ensures:
- Initialized values before use.
- Valid array index access.
- Memory access within lifetime.
- Safe concurrent memory access.
Unsafe APIs (e.g., "unsafe") require manual safety checks.
Error Handling
Manage errors with throws, try, do, catch:
enum GameError: Error {
case noPlayers
case invalidMove(String)
}
func startGame() throws {
throw GameError.invalidMove("Invalid position")
}
do {
try startGame()
} catch GameError.noPlayers {
print("Need players to start")
} catch GameError.invalidMove(let move) {
print("Error: \(move)")
}
// Prints: Error: Invalid positionAssertions and Preconditions
- Assertions: Debug-only checks:
let level = -1
assert(level > 0, "Level must be positive") // Fails in debug- Preconditions: Checked in debug and production:
precondition(index >= 0, "Index must be non-negative")- Fatal Errors: Always halt:
fatalError("Feature not implemented")Assertions and preconditions ensure valid program states, aiding debugging and reliability.