Swift Reference
0. Basics
0.1 Hello World
// print adds a newline
print("Hello, World!")
TERMINAL OUTPUT
Hello, World!
0.2 Building & Running
Swift can be run as a script or compiled.
# Run as script
swift main.swift
# Compile to binary
swiftc main.swift -o main
./main
TERMINAL OUTPUT
Hello, World!
0.3 Comments
// Single-line comment
/* Multi-line
comment */
/// Documentation comment
TERMINAL OUTPUT
(No output)
0.4 Imports
import Foundation
import Network
import SQLite3
TERMINAL OUTPUT
(No output)
0.5 Exit Codes
import Foundation
// Exit with status 1
exit(1)
TERMINAL OUTPUT
(Process exits with status 1)
0.6 Error Handling
enum MyError: Error { case failure }
func task() throws { throw MyError.failure }
do {
try task()
} catch {
print("Caught: \(error)")
}
TERMINAL OUTPUT
Caught: failure
1. Environment & Time
1.1 Variable Declaration
let constant = 10 // Immutable
var mutable = 20 // Mutable
let typed: Int = 5 // Explicit type
TERMINAL OUTPUT
(No output)
1.2 Integer Types
let i: Int = 100 // Platform dependent width
let i64: Int64 = 1000 // Explicit 64-bit
let u8: UInt8 = 255 // Unsigned 8-bit
TERMINAL OUTPUT
(No output)
1.3 Casting
let s = "123"
let i = Int(s) // Optional(123)
let d = Double(i ?? 0)
// Type casting
let val: Any = "Hello"
let str = val as? String
TERMINAL OUTPUT
(No output)
1.4 Truthiness
Swift is strictly boolean. No implicit conversion from Int or String.
let x = 1
if x != 0 { print("True") }
TERMINAL OUTPUT
True
1.5 Environment Vars
import Foundation
let path = ProcessInfo.processInfo.environment["PATH"]
TERMINAL OUTPUT
(No output)
1.6 Time
import Foundation
let now = Date()
let formatter = ISO8601DateFormatter()
print(formatter.string(from: now))
// Monotonic clock (Swift 5.7+)
let clock = ContinuousClock()
let elapsed = clock.measure { /* work */ }
TERMINAL OUTPUT
2024-05-16T12:00:00Z (example)
2. Operators & Regex
2.1 Arithmetic/Logic
let a = 10 / 3 // 3
let b = 10.0 / 3.0 // 3.333...
let c = true && false
let d = !true
TERMINAL OUTPUT
(No output)
2.2 Regex
import Foundation
// Modern Regex (Swift 5.7+)
let regex = /\d+/
if let match = "price: 100".firstMatch(of: regex) {
print(match.0)
}
TERMINAL OUTPUT
100
3. Argument Parsing
3.1 CLI Argument Parsing
import Foundation
let args = CommandLine.arguments
if args.count > 1 {
print("First arg: \(args[1])")
}
TERMINAL OUTPUT
(Depends on input)
4. Functions & Memory
4.1 Declaration/Returns
func add(a: Int, b: Int = 0) -> Int {
return a + b
}
// Multi-return via Tuple
func getStatus() -> (Int, String) {
return (200, "OK")
}
TERMINAL OUTPUT
(No output)
4.2 References/Pointers
ARC (Automatic Reference Counting). Classes are reference types; structs/enums are value types.
class Person { var name = "" }
struct Point { var x = 0 }
// Manual memory (rarely needed)
let ptr = UnsafeMutablePointer<Int>.allocate(capacity: 1)
ptr.pointee = 42
ptr.deallocate()
TERMINAL OUTPUT
(No output)
5. Loops & Iteration
5.1 Basic Loops
for i in 1...3 { print(i) } // 1, 2, 3
for i in 0..<3 { print(i) } // 0, 1, 2
var x = 0
while x < 2 { x += 1 }
TERMINAL OUTPUT
1
2
3
0
1
2
5.2 Break/Continue
for i in 1...5 {
if i == 2 { continue }
if i == 4 { break }
print(i)
}
TERMINAL OUTPUT
1
3
5.3 Iterating Collections
let list = ["a", "b"]
for (index, val) in list.enumerated() {
print("\(index): \(val)")
}
TERMINAL OUTPUT
0: a
1: b
6. Strings & Files
6.1 Manipulation
let s = " hello "
let trimmed = s.trimmingCharacters(in: .whitespaces)
let upper = trimmed.uppercased()
let joined = ["a", "b"].joined(separator: "-")
TERMINAL OUTPUT
(No output)
6.2 Path Joining
import Foundation
let url = URL(fileURLWithPath: "/tmp").appendingPathComponent("test.txt")
print(url.path)
TERMINAL OUTPUT
/tmp/test.txt
6.3 Streaming I/O
import Foundation
if let handle = FileHandle(forReadingAtPath: "data.bin") {
defer { handle.closeFile() }
while let chunk = try? handle.read(upToCount: 4096), !chunk.isEmpty {
// Process Data chunk
}
}
TERMINAL OUTPUT
(No output)
6.4 Read to Memory
import Foundation
let content = try? String(contentsOfFile: "file.txt", encoding: .utf8)
let data = try? Data(contentsOf: URL(fileURLWithPath: "file.txt"))
TERMINAL OUTPUT
(No output)
7. Binary & Bitwise
7.1 Allocation/Packing
import Foundation
var data = Data(count: 12)
var val: Int32 = 42
withUnsafeBytes(of: val) { data.replaceSubrange(0..<4, with: $0) }
TERMINAL OUTPUT
(No output)
7.2 Bitwise Ops
let a = 0b1010 & 0b1100 // 0b1000
let b = 0b1010 | 0b1100 // 0b1110
let c = 1 << 3 // 8
TERMINAL OUTPUT
(No output)
7.3 Hex Conversion
let hex = String(255, radix: 16) // "ff"
let val = Int("ff", radix: 16) // 255
TERMINAL OUTPUT
(No output)
8. Collections & JSON
8.1 Lists/Maps/Sets
let arr = [1, 2] // Array
let dict = ["k": "v"] // Dictionary
let set: Set = [1, 2, 2] // Set {1, 2}
TERMINAL OUTPUT
(No output)
8.2 JSON Parsing
import Foundation
struct User: Codable { let id: Int }
let json = "{\"id\": 42}".data(using: .utf8)!
let user = try? JSONDecoder().decode(User.self, from: json)
TERMINAL OUTPUT
(No output)
9. Systems & Networking
9.1 TCP
import Network
let conn = NWConnection(host: "example.com", port: 80, using: .tcp)
conn.start(queue: .main)
conn.send(content: "GET / HTTP/1.0\r\n\r\n".data(using: .utf8), completion: .contentProcessed({ _ in }))
TERMINAL OUTPUT
(No output)
9.2 UDP
import Network
let conn = NWConnection(host: "127.0.0.1", port: 8080, using: .udp)
conn.start(queue: .main)
TERMINAL OUTPUT
(No output)
9.3 Concurrency
import Foundation
// GCD
DispatchQueue.global().async {
print("In background")
}
// Swift Concurrency (async/await)
Task {
print("In Task")
}
TERMINAL OUTPUT
In background
In Task
9.4 SQLite
import SQLite3
var db: OpaquePointer?
sqlite3_open(":memory:", &db)
sqlite3_exec(db, "CREATE TABLE t(id INT)", nil, nil, nil)
sqlite3_close(db)
TERMINAL OUTPUT
(No output)