30 Days of SwiftUI — Day 2: Understanding Collections and Enums in Swift
Introduction
As we continue our SwiftUI learning journey, understanding how to store and organize data efficiently is crucial. Today, we’ll explore arrays, dictionaries, sets, enums, and type annotations — fundamental concepts that make data handling easier and more structured in Swift.
Storing Ordered Data in Arrays
An array is a collection that stores data in an ordered manner. Arrays allow duplicates and maintain the order of elements.
Creating an Array
var fruits = ["Apple", "Banana", "Mango"]
Alternatively, you can define an array with explicit type annotation:
var numbers: [Int] = [10, 20, 30, 40]
Accessing Elements
You can access elements using index positions (starting from 0
):
print(fruits[1]) // Output: Banana
Modifying an Array
fruits.append("Orange") // Adds "Orange" at the end
fruits.remove(at: 0) // Removes "Apple"
print(fruits) // Output: ["Banana", "Mango", "Orange"]
Storing and Finding Data in Dictionaries
A dictionary is a collection that stores data in key-value pairs, allowing for fast lookups.
Creating a Dictionary
var studentScores = ["Alice": 90, "Bob": 85, "Charlie": 88]
Accessing Values
print(studentScores["Alice"]) // Output: Optional(90)
Since a key may not exist, Swift returns an Optional
. You can safely unwrap it using if let
:
if let score = studentScores["Bob"] {
print("Bob's score is \(score)")
}
Modifying a Dictionary
studentScores["David"] = 92 // Adding a new key-value pair
studentScores["Alice"] = 95 // Updating an existing value
print(studentScores)
Using Sets for Fast Data Lookup
A set is an unordered collection that ensures unique values and provides fast lookup times.
Creating a Set
var uniqueNumbers: Set<Int> = [1, 2, 3, 4, 5]
Adding and Removing Elements
uniqueNumbers.insert(6)
uniqueNumbers.remove(3)
print(uniqueNumbers) // Output: Unordered set of numbers
Checking Membership
print(uniqueNumbers.contains(4)) // Output: true
Sets are highly efficient for checking membership compared to arrays.
Creating and Using Enums
An enum (enumeration) defines a type with a fixed set of related values, making code safer and more readable.
Declaring an Enum
enum Weather {
case sunny, rainy, cloudy, windy
}
Using an Enum
var todayWeather = Weather.sunny
Switch Case with Enums
switch todayWeather {
case .sunny:
print("It's a bright day!")
case .rainy:
print("Don't forget an umbrella!")
case .cloudy, .windy:
print("Mild weather today.")
}
Using Type Annotations
Type annotations explicitly specify the data type of a variable or constant.
Example:
let age: Int = 25
var name: String = "Gati"
var isActive: Bool = true
While Swift can infer types, annotations improve code clarity, especially in functions and complex data structures.
Conclusion
Today, we explored arrays, dictionaries, sets, enums, and type annotations, essential tools for organizing and managing data in Swift. These concepts will help us build robust SwiftUI applications.
Follow me on Linkedin: igatitech 🚀🚀🚀
Comments
Post a Comment