Here are 100 Swift practice problems with solutions, covering language fundamentals, optionals, closures, enums, structs/classes, protocols, generics, error handling, concurrency, and algorithms.
Also try it: 100 Rust practice problems with solutions
1. Hello World
Write a program that prints “Hello, World!”.
swift
print("Hello, World!")
2. Variables and Constants
Declare an immutable let constant name with the value "Alice" and a mutable var variable age with the value 30, then print them.
swift
let name = "Alice"
var age = 30
print("\(name) is \(age) years old")
3. Basic Function
Write a function add that takes two integers and returns their sum.
swift
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
print(add(3, 5)) // 8
4. Function with External Parameter Names
Write a function greet(person:) that returns a greeting string.
swift
func greet(person name: String) -> String {
return "Hello, \(name)"
}
print(greet(person: "Bob"))
5. Default Parameter Values
Write a function multiply that takes two integers with the second defaulting to 1.
swift
func multiply(_ a: Int, _ b: Int = 1) -> Int {
return a * b
}
print(multiply(4)) // 4
print(multiply(4, 5)) // 20
6. Variadic Parameters
Write a function average that accepts any number of Double values and returns the mean.
swift
func average(_ numbers: Double...) -> Double {
guard !numbers.isEmpty else { return 0 }
return numbers.reduce(0, +) / Double(numbers.count)
}
7. In-Out Parameters
Swap two integers using an in-out parameter.
swift
func swap(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var x = 10, y = 20
swap(&x, &y)
print(x, y) // 20 10
8. If-Else
Check if a number is even or odd.
swift
func evenOrOdd(_ n: Int) -> String {
if n % 2 == 0 {
return "even"
} else {
return "odd"
}
}
9. Switch Statement
Write a function that returns the name of a weekday given its number (1…7).
swift
func weekdayName(_ day: Int) -> String {
switch day {
case 1: return "Monday"
case 2: return "Tuesday"
case 3: return "Wednesday"
case 4: return "Thursday"
case 5: return "Friday"
case 6: return "Saturday"
case 7: return "Sunday"
default: return "Invalid"
}
}
10. For-In Loop with Range
Print numbers 1 to 5.
swift
for i in 1...5 {
print(i)
}
11. While Loop
Compute factorial of 5 using a while loop.
swift
var n = 5, fact = 1
while n > 0 {
fact *= n
n -= 1
}
print(fact) // 120
12. Repeat-While
Print numbers from 10 down to 1 using repeat-while.
swift
var num = 10
repeat {
print(num)
num -= 1
} while num > 0
13. Arrays
Create an array of strings, append an element, and access values.
swift
var fruits = ["Apple", "Banana"]
fruits.append("Orange")
print(fruits[1]) // Banana
14. Iterate Over Array with Index
Print array elements with their index using enumerated().
swift
let colors = ["red", "green", "blue"]
for (index, color) in colors.enumerated() {
print("\(index): \(color)")
}
15. Dictionaries
Create a dictionary of stock codes (String: Int), add a key, and retrieve a value with optional binding.
swift
var stock = ["AAPL": 150, "GOOG": 2800]
stock["MSFT"] = 300
if let applePrice = stock["AAPL"] {
print("Apple: \(applePrice)")
}
16. Sets
Create a set of integers and check for membership.
swift
var primes: Set = [2, 3, 5, 7] primes.insert(11) print(primes.contains(5)) // true
17. Optionals
Declare an optional string and safely unwrap using if let.
swift
var optionalName: String? = "John"
if let name = optionalName {
print("Hello, \(name)")
}
18. Nil-Coalescing Operator
Provide a default value for an optional.
swift
let nickname: String? = nil let displayName = nickname ?? "Anonymous" print(displayName)
19. Guard Statement
Write a function that prints a greeting only if the optional name is non‑nil; otherwise exits.
swift
func greet(_ name: String?) {
guard let name = name else {
print("No name provided")
return
}
print("Hello, \(name)")
}
20. Optional Chaining
Access the length of a string through an optional instance.
swift
struct Person {
var name: String
}
var person: Person? = Person(name: "Alice")
let nameLength = person?.name.count // Optional<Int>
print(nameLength ?? 0)
21. Implicitly Unwrapped Optional
Declare an implicitly unwrapped optional and use it.
swift
var email: String! = "test@example.com" print(email.count) // no need to unwrap
22. Map, Filter, Reduce
Given an array of integers, filter even, map to string, and reduce to a single string joined by commas.
swift
let numbers = [1, 2, 3, 4, 5, 6]
let result = numbers.filter { $0 % 2 == 0 }
.map { "\($0)" }
.joined(separator: ",")
print(result) // "2,4,6"
23. Reduce to Sum
Compute sum of an array using reduce.
swift
let nums = [10, 20, 30, 40] let total = nums.reduce(0, +) print(total) // 100
24. Sort with Closure
Sort an array of strings by length.
swift
let words = ["apple", "pie", "banana", "kiwi"]
let sorted = words.sorted { $0.count < $1.count }
print(sorted) // ["pie", "kiwi", "apple", "banana"]
25. Trailing Closure Syntax
Use the sorted(by:) method with trailing closure.
swift
let numbers2 = [5, 2, 8, 3]
let descending = numbers2.sorted { a, b in
return a > b
}
print(descending)
26. Closures Capturing Values
Create a function that returns a closure that increments a counter.
swift
func makeIncrementer(amount: Int) -> () -> Int {
var total = 0
return {
total += amount
return total
}
}
let incByTwo = makeIncrementer(amount: 2)
print(incByTwo()) // 2
print(incByTwo()) // 4
27. Escaping Closure
Write a function that takes an escaping closure and stores it to execute later.
swift
class TaskManager {
var completionHandlers: [() -> Void] = []
func addTask(completion: @escaping () -> Void) {
completionHandlers.append(completion)
}
func runAll() {
completionHandlers.forEach { $0() }
}
}
28. Autoclosures
Use @autoclosure to delay evaluation.
swift
func debugLog(_ message: @autoclosure () -> String) {
#if DEBUG
print(message())
#endif
}
debugLog("App started")
29. Struct Basics
Create a Rectangle struct with width and height properties.
swift
struct Rectangle {
var width: Double
var height: Double
}
let rect = Rectangle(width: 10, height: 5)
30. Struct Computed Property
Add a computed property area to Rectangle and a read‑only perimeter.
swift
extension Rectangle {
var area: Double { width * height }
var perimeter: Double { 2 * (width + height) }
}
31. Struct Methods
Add a method biggerThan(width:height:) that returns true if area is bigger than another rectangle.
swift
extension Rectangle {
func biggerThan(_ other: Rectangle) -> Bool {
return self.area > other.area
}
}
32. Lazy Stored Properties
Define a struct with a property that is computed lazily (costly operation simulated).
swift
struct DataImporter {
init() { print("Importing data...") }
var filename = "data.txt"
}
struct Manager {
lazy var importer = DataImporter()
var data: [String] = []
}
var manager = Manager()
manager.data.append("Entry")
print(manager.importer.filename) // triggers init
33. Property Observers
Add willSet and didSet to a stepCount property.
swift
class StepCounter {
var steps: Int = 0 {
willSet(newTotal) {
print("About to set steps to \(newTotal)")
}
didSet {
if steps > oldValue {
print("Added \(steps - oldValue) steps")
}
}
}
}
let counter = StepCounter()
counter.steps = 100
34. Type Properties (Static)
Create a struct with a static property to count instances.
swift
struct User {
static var count = 0
var name: String
init(name: String) {
self.name = name
User.count += 1
}
}
let u1 = User(name: "Alice")
let u2 = User(name: "Bob")
print(User.count) // 2
35. Enums – Basic
Define an enum for compass directions and match with a switch.
swift
enum Compass {
case north, south, east, west
}
let direction = Compass.east
switch direction {
case .north: print("North")
case .south: print("South")
case .east: print("East")
case .west: print("West")
}
Also try it: 100 kotlin practice problems with solutions
36. Raw Values in Enums
Assign raw values (String) to an enum.
swift
enum Planet: Int {
case mercury = 1, venus, earth, mars
}
let earth = Planet(rawValue: 3) // Optional<Planet>
print(earth?.rawValue ?? -1)
37. Associated Values
Define an enum Barcode with associated values and switch on it.
swift
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
let productCode = Barcode.upc(8, 85909, 51226, 3)
switch productCode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem) \(manufacturer) \(product) \(check)")
case .qrCode(let productCode):
print("QR: \(productCode)")
}
38. Enum Methods
Add a method to a TrafficLight enum that returns the next light.
swift
enum TrafficLight {
case red, yellow, green
mutating func next() {
switch self {
case .red: self = .green
case .yellow: self = .red
case .green: self = .yellow
}
}
}
var light = TrafficLight.red
light.next() // green
39. Recursive Enums
Model a simple arithmetic expression with indirect enum.
swift
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
40. Class Inheritance
Create a base class Vehicle and a subclass Car that overrides a method.
swift
class Vehicle {
var currentSpeed = 0.0
func description() -> String {
return "traveling at \(currentSpeed) mph"
}
}
class Car: Vehicle {
var gear = 1
override func description() -> String {
return super.description() + " in gear \(gear)"
}
}
41. Initializers in Classes
Use designated and convenience initializers.
swift
class Food {
var name: String
init(name: String) { self.name = name }
convenience init() { self.init(name: "[Unnamed]") }
}
42. Failable Initializer
Create an init? that returns nil if the input is invalid.
swift
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
43. Deinitializers
Define a class that prints a message when deinitialized.
swift
class Logger {
let name: String
init(name: String) { self.name = name }
deinit { print("\(name) is being deinitialized") }
}
44. Type Casting (is, as?)
Use is to check type and as? to downcast.
swift
class MediaItem {}
class Movie: MediaItem {
var director = ""
}
class Song: MediaItem {
var artist = ""
}
let library: [MediaItem] = [Movie(), Song()]
for item in library {
if item is Movie { print("Movie") }
if let song = item as? Song {
print("Song by \(song.artist)")
}
}
45. Protocol Definition and Conformance
Define a protocol FullyNamed with a property fullName: String and conform a struct.
swift
protocol FullyNamed {
var fullName: String { get }
}
struct Person: FullyNamed {
var firstName: String
var lastName: String
var fullName: String { return "\(firstName) \(lastName)" }
}
46. Protocol Extension with Default Implementation
Extend FullyNamed to provide a default greeting.
swift
extension FullyNamed {
func greet() -> String {
return "Hello, \(fullName)"
}
}
47. Protocol Inheritance
Define Payable and NeedsTraining protocols and a SkilledWorker protocol that inherits from both.
swift
protocol Payable {
func calculateWages() -> Int
}
protocol NeedsTraining {
func study()
}
protocol SkilledWorker: Payable, NeedsTraining {}
48. Generic Function
Write a generic function that swaps two values.
swift
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
(a, b) = (b, a)
}
49. Generic Stack
Implement a generic Stack struct with push, pop, and peek.
swift
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ item: Element) { items.append(item) }
mutating func pop() -> Element? { items.popLast() }
func peek() -> Element? { items.last }
}
50. Generic Where Clause
Extend Stack to provide an isTop method only when the element is equatable.
swift
extension Stack where Element: Equatable {
func isTop(_ item: Element) -> Bool {
return peek() == item
}
}
51. Error Handling (Throws)
Write a function that splits a string into two parts by a delimiter and throws if delimiter not found.
swift
enum SplittingError: Error {
case delimiterNotFound
}
func split(_ s: String, delimiter: Character) throws -> (String, String) {
guard let index = s.firstIndex(of: delimiter) else {
throw SplittingError.delimiterNotFound
}
let firstPart = String(s[..<index])
let secondPart = String(s[s.index(after: index)...])
return (firstPart, secondPart)
}
do {
let parts = try split("hello-world", delimiter: "-")
print(parts)
} catch {
print(error)
}
52. Try? and Try!
Use try? to convert to optional and try! only when certain.
swift
let resultOptional = try? split("hello-world", delimiter: "-")
let resultForced = try! split("hello-world", delimiter: "-") // safe here
53. Rethrows
Write a function that takes a throwing closure and rethrows the error.
swift
func executeIfNeeded(_ shouldExecute: Bool, function: () throws -> Void) rethrows {
if shouldExecute {
try function()
}
}
54. ARC and Weak References
Create a class Person with a weak apartment property.
swift
class Apartment {}
class Person2 {
var name: String
weak var apartment: Apartment?
init(name: String) { self.name = name }
deinit { print("\(name) deinit") }
}
55. Unowned References
Use unowned reference when the other instance has the same lifetime.
swift
class Customer {
var name: String
var card: CreditCard?
init(name: String) { self.name = name }
}
class CreditCard {
let number: String
unowned let customer: Customer
init(number: String, customer: Customer) {
self.number = number
self.customer = customer
}
}
56. Closures with Capture Lists
Avoid retain cycle by using [weak self] in a closure.
swift
class ViewController {
var name = "Main"
func configureButton(action: @escaping () -> Void) {}
func setup() {
configureButton { [weak self] in
guard let self = self else { return }
print(self.name)
}
}
}
57. Async/Await (Swift 5.5+)
Write an async function that fetches data from a URL (simulate with delay).
swift
func fetchData() async -> String {
await Task.sleep(1_000_000_000) // 1 second
return "Data"
}
Task {
let data = await fetchData()
print(data)
}
58. Async Throwing
Combine async and throws.
swift
enum NetworkError: Error { case badURL }
func download(from urlString: String) async throws -> String {
guard urlString.starts(with: "https://") else {
throw NetworkError.badURL
}
await Task.sleep(500_000_000)
return "Content from \(urlString)"
}
59. Task Group
Fetch multiple URLs concurrently with withTaskGroup.
swift
func fetchMultipleURLs(_ urls: [String]) async -> [String] {
await withTaskGroup(of: String.self) { group in
for url in urls {
group.addTask { await fetchData() } // simplified
}
var results: [String] = []
for await result in group { results.append(result) }
return results
}
}
60. MainActor
Run UI update on the main actor.
swift
@MainActor func updateUI() {
print("UI updated on main thread")
}
Task {
await updateUI()
}
61. Subscripts
Add a subscript to a TimesTable struct that returns the multiplication result.
swift
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int { multiplier * index }
}
let threeTimesTable = TimesTable(multiplier: 3)
print(threeTimesTable[5]) // 15
62. Protocol Composition
A function that accepts a parameter conforming to two protocols.
swift
protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }
func wishHappyBirthday(to celebrant: Named & Aged) {
print("Happy birthday \(celebrant.name), you're \(celebrant.age)")
}
63. Extensions to Add Convenience Initializer
Extend String to add a custom init? that checks for a valid email.
swift
extension String {
init?(validEmail email: String) {
guard email.contains("@") else { return nil }
self = email
}
}
64. Nested Types
Create a struct containing an enum.
swift
struct Chessboard {
enum Color: String { case white, black }
var color: Color
}
65. Result Type
Use Result to handle success/failure in a function.
swift
func divide(_ a: Double, by b: Double) -> Result<Double, Error> {
guard b != 0 else { return .failure(NSError(domain: "Division by zero", code: 0)) }
return .success(a / b)
}
switch divide(10, by: 2) {
case .success(let value): print(value)
case .failure(let error): print(error)
}
66. Higher-Order Function: forEach
Print each element of an array using forEach.
swift
[1, 2, 3].forEach { print($0) }
67. FlatMap
Use flatMap to flatten a nested array.
swift
let nested = [[1,2], [3,4], [5]]
let flat = nested.flatMap { $0 }
print(flat) // [1,2,3,4,5]
68. CompactMap
Remove nil values from an array of optionals.
swift
let optionalNumbers: [Int?] = [1, nil, 3, nil, 5]
let nonNil = optionalNumbers.compactMap { $0 }
print(nonNil) // [1, 3, 5]
69. First(where:)
Find the first element matching a condition.
swift
let names = ["Alice", "Bob", "Charlie"]
if let firstWithA = names.first(where: { $0.hasPrefix("A") }) {
print(firstWithA) // Alice
}
70. Contains with Condition
Check if any element satisfies a condition.
swift
let ages = [20, 18, 35, 12]
let hasAdult = ages.contains(where: { $0 >= 18 }) // true
71. Custom Reduce Implementation
Write a function that mimics reduce for an array of integers.
swift
func customReduce<T, U>(_ array: [T], _ initial: U, _ combine: (U, T) -> U) -> U {
var result = initial
for element in array { result = combine(result, element) }
return result
}
let sum = customReduce([1,2,3], 0, +)
72. Pattern Matching with if case
Use if case to match an optional enumeration.
swift
enum Media { case book(title: String), movie(title: String) }
let item = Media.book(title: "Swift Programming")
if case .book(let title) = item {
print("Book: \(title)")
}
73. Guard Case
Same with guard.
swift
func handle(_ media: Media) {
guard case .book(let title) = media else { return }
print("Book: \(title)")
}
74. Numeric Type Conversion
Convert a Double to Int and handle possible precision loss.
swift
let pi = 3.14159 let intPi = Int(pi) // truncation
75. Lexicographic String Comparison
Compare strings using localized standard.
swift
print("café".compare("cafe¡", locale: .current) == .orderedSame) // false
76. Date Formatting
Format a Date to a string.
swift
let now = Date() let formatter = DateFormatter() formatter.dateStyle = .short print(formatter.string(from: now))
77. Array of Random Numbers
Generate an array of 5 random integers between 1 and 100.
swift
let randomNumbers = (1...5).map { _ in Int.random(in: 1...100) }
78. Sorting with Key Path
Sort an array of structs by a property.
swift
struct Student { let name: String; let grade: Int }
let students = [Student(name: "Alice", grade: 85), Student(name: "Bob", grade: 92)]
let sorted = students.sorted(by: \.grade)
79. Generic with Numeric Constraint
Write a sum function that only works for Numeric types.
swift
func sumOf<T: Numeric>(_ numbers: [T]) -> T {
return numbers.reduce(0, +)
}
print(sumOf([1,2,3])) // 6
80. Defer Statement
Use defer to ensure a file handle is closed.
swift
func readFile(path: String) {
print("Opening file...")
defer { print("Closing file") }
print("Reading file...")
}
readFile(path: "data.txt")
// Opening file... Reading file... Closing file
81. Filter with KeyPath
Use filter with \. key path.
swift
let items = [Student(name: "A", grade: 70), Student(name: "B", grade: 90)]
let topStudents = items.filter { $0.grade >= 80 }
82. Counting Occurrences
Count the frequency of each character in a string using a dictionary.
swift
let str = "hello"
var freq: [Character: Int] = [:]
for ch in str { freq[ch, default: 0] += 1 }
print(freq) // ["h":1, "e":1, "l":2, "o":1]
83. Palindrome Check
Check if a string is a palindrome (ignore case and non‑letters).
swift
func isPalindrome(_ s: String) -> Bool {
let cleaned = s.lowercased().filter { $0.isLetter }
return cleaned == String(cleaned.reversed())
}
84. Reverse Words in a Sentence
Reverse the words in a sentence but keep word order.
swift
func reverseWords(_ sentence: String) -> String {
return sentence.split(separator: " ")
.map { String($0.reversed()) }
.joined(separator: " ")
}
85. Fibonacci Sequence
Return an array of first n Fibonacci numbers.
swift
func fibonacci(_ n: Int) -> [Int] {
guard n > 0 else { return [] }
var fib = [0, 1]
if n <= 2 { return Array(fib.prefix(n)) }
for _ in 2..<n {
fib.append(fib[fib.count - 1] + fib[fib.count - 2])
}
return fib
}
86. Prime Check
swift
func isPrime(_ n: Int) -> Bool {
guard n >= 2 else { return false }
guard n > 3 else { return true }
let sqrtN = Int(Double(n).squareRoot())
for i in 2...sqrtN {
if n % i == 0 { return false }
}
return true
}
87. GCD (Euclidean)
swift
func gcd(_ a: Int, _ b: Int) -> Int {
var a = a, b = b
while b != 0 { (a, b) = (b, a % b) }
return a
}
Also try it: 100 Pandas practice problems with solutions
88. Binary Search
swift
func binarySearch<T: Comparable>(_ array: [T], target: T) -> Int? {
var low = 0, high = array.count - 1
while low <= high {
let mid = (low + high) / 2
if array[mid] == target { return mid }
else if array[mid] < target { low = mid + 1 }
else { high = mid - 1 }
}
return nil
}
89. FizzBuzz 1 to 100
swift
for i in 1...100 {
if i % 15 == 0 { print("FizzBuzz") }
else if i % 3 == 0 { print("Fizz") }
else if i % 5 == 0 { print("Buzz") }
else { print(i) }
}
90. Shuffle Array
Implement Fisher‑Yates shuffle.
swift
extension Array {
mutating func shuffle() {
for i in stride(from: count - 1, to: 0, by: -1) {
let j = Int.random(in: 0...i)
swapAt(i, j)
}
}
}
91. Find Duplicates
Return duplicate elements from an array (order kept).
swift
func findDuplicates<T: Hashable>(_ arr: [T]) -> [T] {
var seen: Set<T> = []
var duplicates: [T] = []
for item in arr {
if seen.contains(item) { duplicates.append(item) }
else { seen.insert(item) }
}
return duplicates
}
92. Remove Duplicates Preserving Order
swift
func unique<T: Hashable>(_ arr: [T]) -> [T] {
var seen: Set<T> = []
return arr.filter { seen.insert($0).inserted }
}
93. Power (Recursive)
Compute x^n recursively.
swift
func power(_ base: Double, _ exponent: Int) -> Double {
guard exponent != 0 else { return 1 }
if exponent < 0 { return 1 / power(base, -exponent) }
return base * power(base, exponent - 1)
}
94. Memoized Fibonacci (Closure with Cache)
swift
func memoize<T: Hashable, U>(_ body: @escaping ((T) -> U, T) -> U) -> (T) -> U {
var cache = [T: U]()
var result: ((T) -> U)!
result = { x in
if let cached = cache[x] { return cached }
let computed = body(result, x)
cache[x] = computed
return computed
}
return result
}
let fibMemo: (Int) -> Int = memoize { fib, n in
n < 2 ? n : fib(n - 1) + fib(n - 2)
}
print(fibMemo(20))
95. Simple Command-Line Calculator
Read input (simulated) and calculate.
swift
func calculate(_ input: String) -> Double {
let parts = input.split(separator: " ")
guard parts.count == 3, let a = Double(parts[0]), let b = Double(parts[2]) else { return 0 }
switch parts[1] {
case "+": return a + b
case "-": return a - b
case "*": return a * b
case "/": return b != 0 ? a / b : 0
default: return 0
}
}
print(calculate("3 + 4"))
96. Type Alias
Define a typealias for a tuple representing a point.
swift
typealias Point = (x: Double, y: Double) let origin: Point = (0,0)
97. Opaque Return Type (some View style but simpler)
Write a function that returns an opaque type conforming to Comparable.
swift
func makeInt() -> some Comparable {
return 42
}
let val = makeInt()
print(val) // 42
98. Property Wrapper
Create a @Clamped property wrapper that restricts a value to a range.
swift
@propertyWrapper
struct Clamped<Value: Comparable> {
private var value: Value
let range: ClosedRange<Value>
var wrappedValue: Value {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
init(wrappedValue: Value, _ range: ClosedRange<Value>) {
self.range = range
self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
}
struct Player {
@Clamped(0...100) var health: Int
}
var player = Player(health: 80)
player.health = 120
print(player.health) // 100
99. Result Builder (Simple)
Create a @resultBuilder that builds a string by joining lines.
swift
@resultBuilder
struct StringBuilder {
static func buildBlock(_ components: String...) -> String {
components.joined(separator: "\n")
}
}
func makeDescription(@StringBuilder _ content: () -> String) -> String {
content()
}
let desc = makeDescription {
"Name: Alice"
"Age: 30"
}
print(desc)
100. Async Sequence
Write an async sequence that emits numbers 1 to 5 with a delay.
swift
struct Counter: AsyncSequence {
typealias Element = Int
let howHigh: Int
struct AsyncIterator: AsyncIteratorProtocol {
var current = 1
let max: Int
mutating func next() async -> Int? {
guard current <= max else { return nil }
await Task.sleep(500_000_000)
let result = current; current += 1
return result
}
}
func makeAsyncIterator() -> AsyncIterator {
AsyncIterator(max: howHigh)
}
}
Task {
for await number in Counter(howHigh: 5) {
print(number)
}
}
Final Thought
You’ve read the Swift book. You’ve watched the tutorials. But when you open Xcode and stare at a blank editor, a quiet voice whispers: “Am I really cut out for this?”
That self-doubt is deeply human — and it’s exactly the feeling these 100 Swift practice problems will help you gently let go of.
Every challenge here comes wrapped in plain, friendly language and a solution that doesn’t just show you the code — it walks you through the why. You’ll start softly: variables, optionals, loops, and functions. Then you’ll rise into closures, protocols, error handling, and the elegant patterns that make Swift feel like poetry once it clicks.
Programming isn’t just typing — it’s an act of courage, repeated daily. With each solved problem, your fingers learn what your mind once wrestled with. Before long, the language feels less like a mountain and more like a home you’re building for your ideas.
This post was made for the beginner with wobbly confidence and the passionate learner preparing for an iOS interview. Pick one problem today. Let the small wins stack up. The world needs the app only you can imagine. It starts right here, with a single line of Swift code.