Swift Syntax & Variables
Swift Syntax & Variables
Swift is a type-safe, modern programming language designed by Apple for iOS, macOS, watchOS, tvOS, and server-side development. Every Swift program is a collection of statements, and statements are separated by newlines or semicolons (though semicolons are rarely needed).
Constants and Variables
In Swift, you declare constants with let and variables with var. A constant's value cannot be changed after it is set, while a variable can be reassigned.
let maximumAttempts = 10 // constant
var currentAttempt = 1 // variable
currentAttempt = 2 // OK
// maximumAttempts = 11 // compile error
Using let whenever possible is a best practice. It signals intent, helps the compiler optimize, and prevents accidental mutation. You can declare multiple constants or variables on a single line:
let a = 1, b = 2, c = 3
var x = 0, y = 0, z = 0
Naming Variables
Variable and constant names can contain any Unicode character, including emoji, but must not start with a number. Names cannot be the same as reserved keywords unless you escape them with backticks:
let π = 3.14159
let 🐶 = "dog"
let `class` = "reserved" // backticks for keyword
Printing and Debug Output
Use print(_:separator:terminator:) to output values. String interpolation lets you embed expressions inside a string literal:
let name = "Alice"
print("Hello, \(name)!") // "Hello, Alice!"
print("2 + 3 = \(2 + 3)") // "2 + 3 = 5"
Comments
Single-line comments start with //, multi-line comments use /* ... */, and Swift supports nested multi-line comments:
// This is a comment
/* This is
a multi-line
/* nested */ comment */
Semicolons
Swift does not require semicolons at the end of statements, but they are allowed and sometimes useful when writing multiple statements on one line:
let a = 1; let b = 2; print(a + b)
Type Inference
One of Swift's most powerful features is type inference. The compiler can often deduce the type of a variable from its initial value, so explicit type annotations are usually unnecessary:
let answer = 42 // inferred as Int
let pi = 3.14 // inferred as Double
let greeting = "Hello" // inferred as String
let flag = true // inferred as Bool
When precision matters, you can annotate the type explicitly:
let score: Double = 100 // explicitly Double, not Int
let label: String = "A" // explicitly String
Understanding let vs var, basic naming, and type inference forms the foundation of every Swift program you will write.
Types & Type Safety
Types & Type Safety
Swift is a statically typed language, meaning every variable and constant has a type known at compile time. The compiler enforces type safety, preventing you from assigning a value of one type to a variable of another type without an explicit conversion.
Core Scalar Types
Swift provides four fundamental scalar types:
| Type | Description | Example |
|---|---|---|
Int |
64-bit signed integer on most platforms | let count = 42 |
Double |
64-bit floating-point number | let price = 19.99 |
Float |
32-bit floating-point (less common) | let temperature: Float = 72.5 |
Bool |
true or false |
let isActive = true |
String |
A sequence of characters | let name = "Swift" |
Integer Limits
Int is platform-dependent: 64-bit on 64-bit devices, 32-bit on 32-bit. You can also use explicit-width types:
let eightBit: Int8 = 127
let sixteenBit: Int16 = 32_767
let unsigned: UInt8 = 255
Attempting to assign a value outside the range causes a runtime error:
let overflow: Int8 = 128 // Runtime error!
Type Conversion
Swift does not implicitly convert between types. You must be explicit:
let intValue = 42
let doubleValue = Double(intValue) // 42.0
let result = doubleValue + 3.14 // 45.14
Mixing Int and Double in arithmetic requires explicit conversion:
let a: Int = 3
let b: Double = 2.5
let sum = Double(a) + b // 5.5
Type Aliases
You can create alternative names for existing types using typealias:
typealias AudioSample = UInt16
let sample: AudioSample = 32767
This is especially useful when working with Core Audio or other frameworks that use domain-specific type names.
Tuple Types
Tuples group multiple values into a single compound value:
let httpStatus = (200, "OK")
print(httpStatus.0) // 200
print(httpStatus.1) // "OK"
// Named tuple elements
let person = (name: "Alice", age: 30)
print(person.name) // "Alice"
Type Safety in Practice
The compiler catches type errors at compile time:
let message = "Hello"
// let number: Int = message // Compile error!
This prevents an entire class of bugs that plague dynamically typed languages. Swift's type system is powerful enough to infer generic types, support protocol-based polymorphism, and enable advanced patterns like associated types and opaque return types—all while maintaining compile-time safety.
Understanding these core types and Swift's insistence on explicit type relationships is essential before moving on to optionals, collections, and more advanced language features.
String Interpolation & Operators
String Interpolation & Operators
Strings in Swift
Strings in Swift are value types, meaning they are copied when assigned or passed to functions (with copy-on-write optimization under the hood). Strings are collections of characters, supporting Unicode fully.
let empty = ""
let multiLine = """
This is a
multi-line string
"""
Multi-line strings preserve indentation relative to the closing """. You can escape characters with backslash or use string interpolation to embed values.
String Interpolation
String interpolation is Swift's mechanism for embedding expressions inside string literals using \(expression):
let name = "Bob"
let age = 25
let message = "My name is \(name) and I am \(age) years old."
You can embed any valid expression, including function calls and arithmetic:
let price = 9.99
let quantity = 3
print("Total: \(price * Double(quantity))") // "Total: 29.97"
Custom types can customize their string representation by conforming to the CustomStringConvertible protocol:
struct Point {
var x: Double
var y: Double
var description: String {
return "(\(x), \(y))"
}
}
let p = Point(x: 1.0, y: 2.0)
print("Point is at \(p)") // "Point is at (1.0, 2.0)"
Operators
Swift provides several categories of operators:
Arithmetic Operators:
let sum = 5 + 3 // 8
let diff = 10 - 4 // 6
let product = 6 * 7 // 42
let quotient = 10 / 3 // 3 (integer division)
let remainder = 10 % 3 // 1
Comparison Operators:
1 == 1 // true
2 != 3 // true
4 > 3 // true
5 < 6 // true
1 <= 1 // true
6 >= 7 // false
Logical Operators:
!true // false
true && false // false
true || false // true
Ternary Operator:
let max = (a > b) ? a : b
Nil-Coalescing Operator (??):
Used with optionals to provide a default value:
let name: String? = nil
let displayName = name ?? "Anonymous" // "Anonymous"
Range Operators:
let range1 = 0...5 // 0, 1, 2, 3, 4, 5 (closed)
let range2 = 0..<5 // 0, 1, 2, 3, 4 (half-open)
Compound Assignment Operators:
var x = 10
x += 5 // 15
x -= 3 // 12
x *= 2 // 24
Operator Overloading
You can define custom operators for your own types:
struct Vector2D {
var x: Double, y: Double
}
func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
let v1 = Vector2D(x: 1, y: 2)
let v2 = Vector2D(x: 3, y: 4)
let v3 = v1 + v2 // Vector2D(x: 4, y: 6)
Understanding string interpolation and operators gives you the tools to work with data, format output, and express logic clearly in Swift programs.
Quiz
1. What keyword declares a constant in Swift?
2. What is the output of: let x = 10; print("Value is \(x)")
3. Which type is inferred for: let pi = 3.14?
4. What does the nil-coalescing operator `??` do?
5. What is the result of `10 / 3` in Swift?
Flashcards
Question
What is the difference between `let` and `var`?
Click to reveal answer
Answer
`let` declares a constant (immutable), `var` declares a variable (mutable).
Question
How do you embed a value inside a string in Swift?
Click to reveal answer
Answer
Use string interpolation: `\(expression)` inside a string literal.
Question
What is type inference?
Click to reveal answer
Answer
The compiler automatically deduces the type of a variable from its initial value without explicit annotation.
Question
What are the four core scalar types in Swift?
Click to reveal answer
Answer
Int, Double (or Float), String, and Bool.
Question
What is the range operator `0..<5` called?
Click to reveal answer
Answer
Half-open range operator. It includes 0, 1, 2, 3, 4 but excludes 5.
Revision Notes
Key Takeaways
- 1. Prefer `let` over `var` whenever possible
- 2. Swift uses type inference to reduce boilerplate
- 3. String interpolation is `\(expression)`
- 4. Swift does not perform implicit type conversion
- 5. Tuples group multiple values without defining a struct
Interview Tips
- • Be prepared to explain why `let` is preferred over `var`
- • Know the difference between `Int` and `Double` type conversion
- • Understand string interpolation vs concatenation performance
- • Be able to explain Swift's type safety and how it prevents runtime errors
Cheat Sheet
Swift Basics Cheat Sheet
let= constant,var= variable- Core types:
Int,Double,String,Bool - Type inference: compiler deduces type from value
- String interpolation:
\(expression) - Arithmetic:
+,-,*,/,% - Comparison:
==,!=,>,<,>=,<= - Logical:
&&,||,! - Nil-coalescing:
optional ?? default - Ranges:
0...5(closed),0..<5(half-open) - Multi-line strings:
""" ... """