30 Days of SwiftUI - Day 6: Mastering Structs and Property Management in Swift
🏗️ Building Blocks of Swift: Creating Your Own Structs
Structs are a powerful way to build custom data types in Swift. They group related data and functionality in a neat package.
Example:
struct Car {
var brand: String
var year: Int
}
let myCar = Car(brand: "Tesla", year: 2024)
print(myCar.brand) // Output: Tesla
🔎 Struct vs Tuple: What's the Difference?
Feature | Struct | Tuple |
---|---|---|
Named Properties | Yes | Optional |
Methods & Computed Properties | Yes | No |
Flexibility | Highly Flexible | Lightweight & Fixed |
Use structs for complex data models and tuples for quick, lightweight data combinations.
🛠️ Methods vs Functions: Spot the Difference
Functions exist independently, outside of types.
Methods are functions defined inside types (e.g., structs, classes).
Example:
struct Calculator {
func add(a: Int, b: Int) -> Int {
return a + b
}
}
let calc = Calculator()
print(calc.add(a: 3, b: 5)) // Output: 8
🔄 Why Use mutating
Methods?
If a method modifies any properties of a struct, it must be marked as mutating
.
Example:
struct Counter {
var value = 0
mutating func increment() {
value += 1
}
}
var counter = Counter()
counter.increment()
print(counter.value) // Output: 1
🧮 Dynamic Data: Computed Properties in Action
Computed properties are properties that calculate their values dynamically.
Example:
struct Circle {
var radius: Double
var area: Double {
3.14 * radius * radius
}
}
let circle = Circle(radius: 5)
print(circle.area) // Output: 78.5
🤔 Stored vs Computed Properties: Which to Use?
Use stored properties to store fixed values.
Use computed properties when the value is derived from other properties.
📡 Reacting to Change: Property Observers
Swift's property observers let you monitor property changes using willSet
and didSet
.
Example:
struct ProgressTracker {
var progress = 0 {
willSet { print("Progress about to change to \(newValue)") }
didSet { print("Progress changed from \(oldValue) to \(progress)") }
}
}
var tracker = ProgressTracker()
tracker.progress = 50
⚙️ willSet
vs didSet
: When to Use Which?
Use
**willSet**
when you need to act before the value changes.Use
**didSet**
when you need to react after the value changes.
🚀 Custom Initializers: Crafting Personalized Structs
Swift allows you to create custom initializers to set up complex values.
Example:
struct Book {
var title: String
var author: String
init(title: String, author: String) {
self.title = title
self.author = author
}
}
let book = Book(title: "Swift Mastery", author: "Gati Shah")
🔐 Memberwise Initializers in Swift
Swift automatically generates an initializer for structs if no custom one exists.
Example:
struct Laptop {
var brand: String
var model: String
}
let myLaptop = Laptop(brand: "Apple", model: "MacBook Pro")
🙋♀️ Using self
in Methods: Why and When?
Use self
to distinguish between parameter names and property names or to clarify code in closures.
Example:
struct Person {
var name: String
func introduce() {
print("Hello, I'm \(self.name)")
}
}
🚨 Locking It Down: Mastering Access Control
Access control defines who can use your code and how they interact with it.
Modifier | Scope |
private | Accessible only inside the same type |
fileprivate | Accessible within the same file |
internal | Accessible within the same module (default) |
public | Accessible from any module |
open | Same as public, but allows subclassing outside the module |
🔒 Protecting Data: Limiting Access with Access Control
Access control is key to keeping sensitive data secure and controlling your API's usage.
Example:
struct BankAccount {
private var balance: Double = 0
mutating func deposit(amount: Double) {
balance += amount
print("New balance: \(balance)")
}
}
🌍 Why Use Access Control?
Prevent accidental property modifications.
Improve security by limiting data exposure.
Ensure better code structure and clarity.
🧱 Static Properties & Methods: The Power of One
Static properties and methods belong to the type itself rather than an instance.
Example:
struct Configuration {
static let appName = "SwiftMaster"
static func printAppName() {
print("App Name: \(appName)")
}
}
Configuration.printAppName() // Output: App Name: SwiftMaster
📋 Why Use Static Properties & Methods?
Ideal for constants and shared functionality.
Efficient when you don't need individual instances.
✅ Checkpoint Challenge: Test Your Skills!
Question: Create a struct called Rectangle
with width
and height
properties, a method that calculates its area, and a property observer that prints when the width changes.
Answer:
struct Rectangle {
var width: Double {
didSet { print("Width updated to \(width)") }
}
var height: Double
func area() -> Double {
return width * height
}
}
var rect = Rectangle(width: 5, height: 10)
print(rect.area())
rect.width = 8 // Output: Width updated to 8
Comments
Post a Comment