Apple's modern language for iOS, macOS, watchOS, and beyond โ fast, safe by design (its "optionals" system forces you to handle missing values explicitly), and the only real path into Apple's app ecosystem. Copy-paste examples plus live Run/Submit exercises.
print("Hello, world!")
let age = 25 // let = constant, can't change
var name = "Sam" // var = can change
let price: Double = 19.99
Swift's signature safety feature โ a value that might be missing must be declared with ?, forcing you to handle the "nothing" case.
var middleName: String? = nil
if let m = middleName {
print(m)
} else {
print("no middle name")
}
let age = 20
if age >= 18 {
print("Adult")
} else if age >= 13 {
print("Teen")
} else {
print("Child")
}
for i in 0..<5 {
print(i)
}
var n = 3
while n > 0 {
print(n)
n -= 1
}
var nums = [10, 20, 30]
nums.append(40)
print(nums[0]) // 10
print(nums.count) // 4
var ages = ["Sam": 25, "Ana": 30]
print(ages["Sam"]!) // 25 โ force-unwrap since dict lookups are optional
ages["Lee"] = 40
Swift favors structs (value types) over classes for most everyday data modeling.
struct Dog {
let name: String
let age: Int
func bark() {
print("\(name) says woof!")
}
}
// let d = Dog(name: "Rex", age: 3); d.bark()
Full runnable programs, compiled and run in a real Swift sandbox โ same workspace as the other cheat sheets.
let nums = [4, 8, 15, 16, 23, 42]
var sum = 0
for n in nums { sum += n }
print(sum)
func reverseStr(_ s: String) -> String {
return String(s.reversed())
}
print(reverseStr("swift"))
for i in 1...15 {
if i % 15 == 0 {
print("FizzBuzz")
} else if i % 3 == 0 {
print("Fizz")
} else if i % 5 == 0 {
print("Buzz")
} else {
print(i)
}
}
let text = "the cat sat on the mat the cat ran"
var counts: [String: Int] = [:]
for word in text.split(separator: " ") {
counts[String(word), default: 0] += 1
}
for (word, n) in counts {
print("\(word): \(n)")
}