Learn Swift - 11 Code Examples & CST Typing Practice Test
Swift is a powerful, general-purpose, compiled programming language developed by Apple for iOS, macOS, watchOS, tvOS, and Linux. It emphasizes safety, performance, and modern programming practices.
Learn SWIFT with Real Code Examples
Updated Nov 21, 2025
Code Sample Descriptions
Swift Optionals and Closures
import Foundation
struct Person {
let name: String
let age: Int
var email: String?
}
class PersonManager {
private var people: [Person] = []
func addPerson(_ person: Person) {
people.append(person)
}
func findPeople(matching predicate: (Person) -> Bool) -> [Person] {
return people.filter(predicate)
}
func updateEmail(for name: String, newEmail: String) -> Bool {
if let index = people.firstIndex(where: { $0.name == name }) {
people[index].email = newEmail
return true
}
return false
}
}
// Usage example
let manager = PersonManager()
let people = [
Person(name: "Alice", age: 25, email: "alice@example.com"),
Person(name: "Bob", age: 30, email: nil),
Person(name: "Charlie", age: 35, email: "charlie@example.com")
]
people.forEach { manager.addPerson($0) }
let adults = manager.findPeople { $0.age >= 30 }
print("Adults: \(adults.map { $0.name })")
// Optional binding
for person in adults {
if let email = person.email {
print("\(person.name): \(email)")
} else {
print("\(person.name): No email")
}
}
Demonstrates Swift's type safety, optionals, and closure syntax with a practical example.
Swift Counter with Closures
var count = 0
let updateUI: () -> Void = {
print("Counter: \(count)")
}
let increment: () -> Void = {
count += 1
updateUI()
}
let decrement: () -> Void = {
count -= 1
updateUI()
}
// Simulate actions
updateUI()
increment()
increment()
decrement()
Demonstrates a simple counter using Swift variables and closures.
Swift Theme Toggle
var isDark = false
let updateUI: () -> Void = {
print("Theme: \(isDark ? "Dark" : "Light")")
}
let toggleTheme: () -> Void = {
isDark.toggle()
updateUI()
}
// Simulate actions
updateUI()
toggleTheme()
toggleTheme()
Toggles a dark/light theme using Swift booleans and closures.
Swift Score Tracker
var score = 0
let updateUI: () -> Void = { print("Score: \(score)") }
let increment: () -> Void = { score += 10; updateUI() }
let decrement: () -> Void = { score -= 5; updateUI() }
let reset: () -> Void = { score = 0; updateUI() }
// Simulate actions
updateUI()
increment()
decrement()
reset()
Tracks a score with increment, decrement, and reset closures.
Swift Optional Binding Example
let names: [String?] = ["Alice", nil, "Charlie"]
for name in names {
if let unwrapped = name {
print("Hello, \(unwrapped)")
} else {
print("Name not provided")
}
}
Demonstrates optional binding with Swift optionals.
Swift Health Tracker
var health = 100
let updateUI: () -> Void = { print("Health: \(health)") }
let damage: () -> Void = { health -= 20; updateUI() }
let heal: () -> Void = { health += 10; updateUI() }
// Simulate actions
updateUI()
damage()
heal()
Tracks health with closures for damage and healing actions.
Swift Level Tracker
var level = 1
let updateUI: () -> Void = { print("Level: \(level)") }
let nextLevel: () -> Void = { level += 1; updateUI() }
let resetLevel: () -> Void = { level = 1; updateUI() }
// Simulate actions
updateUI()
nextLevel()
nextLevel()
resetLevel()
Tracks game levels with closures to increment and reset.
Swift Coin Counter
var coins = 0
let updateUI: () -> Void = { print("Coins: \(coins)") }
let collectCoin: () -> Void = { coins += 1; updateUI() }
let loseCoin: () -> Void = { coins -= 1; updateUI() }
// Simulate actions
updateUI()
collectCoin()
collectCoin()
loseCoin()
Counts coins collected and lost using Swift closures.
Swift Ammo Tracker
var ammo = 10
let updateUI: () -> Void = { print("Ammo: \(ammo)") }
let shoot: () -> Void = { ammo -= 1; updateUI() }
let reload: () -> Void = { ammo = 10; updateUI() }
// Simulate actions
updateUI()
shoot()
shoot()
reload()
Tracks ammo usage with closures for shoot and reload actions.
Swift Star Collector
var stars = 0
let updateUI: () -> Void = { print("Stars: \(stars)") }
let collectStar: () -> Void = { stars += 1; updateUI() }
let loseStar: () -> Void = { stars -= 1; updateUI() }
// Simulate actions
updateUI()
collectStar()
collectStar()
loseStar()
Counts collected stars and displays progress using closures.
Swift Power-Up Timer
var powerTime = 10
let updateUI: () -> Void = { print("Power-Up Time: \(powerTime)") }
let tick: () -> Void = { powerTime -= 1; updateUI() }
let resetPower: () -> Void = { powerTime = 10; updateUI() }
// Simulate actions
updateUI()
tick()
tick()
resetPower()
Counts down power-up duration and resets using closures.
Frequently Asked Questions about Swift
What is Swift?
Swift is a powerful, general-purpose, compiled programming language developed by Apple for iOS, macOS, watchOS, tvOS, and Linux. It emphasizes safety, performance, and modern programming practices.
What are the primary use cases for Swift?
iOS app development. macOS desktop applications. watchOS and tvOS apps. Server-side applications using Swift on Linux. Cross-platform development with SwiftUI or server frameworks
What are the strengths of Swift?
Fast and efficient compiled language. Safe programming with fewer runtime crashes. Strong Apple ecosystem support. Modern and readable syntax. Active community and evolving language features
What are the limitations of Swift?
Primarily focused on Apple platforms. Limited third-party libraries compared to older languages. Requires Xcode for full IDE support. Smaller server-side ecosystem than Node.js or Java. Frequent updates may require code adjustments
How can I practice Swift typing speed?
CodeSpeedTest offers 11+ real Swift code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.