Introduction
Welcome back, developer! Today, we're diving into Swift control flow, covering:
-
if
andswitch
statements -
for
andwhile
loops - Optionals (
?
and!
)
To keep things fun, we're building a Fart Rating App. Users will submit a fart sound, and we’ll rate it based on its "intensity" using loops, conditionals, and optionals. 💨😂
Step 1: Create a New SwiftUI Project
- Open Xcode.
- Select Create a new Xcode project.
- Choose App under iOS.
- Name it
FartRater
. - Select SwiftUI as the interface and Swift as the language.
- Click Create! 🚀
Step 2: Understanding Control Flow
If Statements in Swift
Swift uses if
statements to make decisions.
let intensity = 7
if intensity > 8 {
print("Wow, that’s a nuclear fart! 💀")
} else if intensity > 5 {
print("That’s a solid one! 👌")
} else {
print("Barely a whisper. 😴")
}
Switch Statements
A switch
is great for multiple conditions.
let rating = 3
switch rating {
case 1: print("Barely a squeak! 🐭")
case 2...4: print("Respectable effort. 😎")
case 5...7: print("That’s a real contender! 🔥")
case 8...10: print("Call the authorities! 🚨")
default: print("Invalid rating.")
}
Step 3: Designing the UI
Modify ContentView.swift
to create the app UI.
import SwiftUI
struct ContentView: View {
@State private var intensity: Int? = nil
@State private var rating: String = ""
var body: some View {
VStack {
Text("Fart Rater")
.font(.largeTitle)
.padding()
Button("Generate Random Fart") {
intensity = Int.random(in: 1...10)
rating = rateFart(intensity: intensity!)
}
.padding()
.background(Color.green)
.foregroundColor(.white)
.clipShape(Capsule())
if let intensity = intensity {
Text("Fart Intensity: \(intensity)")
.font(.title2)
.padding()
Text(rating)
.font(.title)
.bold()
}
}
}
}
Step 4: Implementing the Rating Logic
We need a function to rate the fart. This uses optionals, switch statements, and loops:
func rateFart(intensity: Int) -> String {
var message = ""
switch intensity {
case 1:
message = "Barely a squeak! 🐭"
case 2...4:
message = "Respectable effort. 😎"
case 5...7:
message = "That’s a real contender! 🔥"
case 8...10:
message = "Call the authorities! 🚨"
default:
message = "Invalid rating."
}
// Adding dramatic effect with a loop
for _ in 1...intensity {
print("💨")
}
return message
}
Step 5: Run and Test
- Click Run (
Cmd + R
) in Xcode. - Tap Generate Random Fart.
- See the intensity and rating displayed.
Next Steps
✅ You built a Fart Rating App! You now understand:
-
if
statements andswitch
for decision-making - Loops (
for
) for repetition - Optionals (
?
,!
) for handling missing values
Next up: "Functions and Closures in Swift" 🚀