Arrays and Dictionaries
Arrays and dictionaries are two fundamental collection types in Swift that allow you to store multiple values in a single variable. While arrays are ordered collections of items, dictionaries store key-value pairs in an unordered manner. This section will guide you through the basics of using arrays and dictionaries in Swift.
Arrays
Declaring Arrays
Arrays in Swift are declared using square brackets []
, and they can contain elements of the same type.
var numbers: [Int] = [1, 2, 3]
Accessing Elements
You can access elements in an array using their index, starting from 0.
let firstNumber = numbers[0] // Output: 1
Modifying Arrays
Arrays are mutable if declared with var
. You can add, remove, or change elements.
numbers.append(4) // Adds 4 to the end
numbers.remove(at: 0) // Removes the first element
Dictionaries
Declaring Dictionaries
Dictionaries are declared using square brackets []
with a colon :
separating the key and value types.
var person: [String: String] = ["name": "John", "age": "30"]
Accessing Elements
You can access dictionary values using their keys.
let name = person["name"] // Output: Optional("John")
Modifying Dictionaries
Like arrays, dictionaries are mutable if declared with var
.
person["age"] = "31" // Updates the age to 31
person["city"] = "New York" // Adds a new key-value pair
Conclusion
Arrays and dictionaries are essential tools for any Swift developer. They provide flexible and efficient ways to manage collections of data. Understanding how to declare, access, and manipulate these collections will help you write more robust and readable Swift code.
Book a conversation with us for personalize training today!