Intern
When will you use arrays in your code?
sobes.tech AI
Answer from AI
Arrays are used when it is necessary to store an ordered collection of homogeneous elements, accessed by index. Typical scenarios include:
- Storing a list of objects where order matters (e.g., a list of users, a list of tasks in an application).
- Operations requiring quick access to elements by their position.
- Iterating over all elements of a collection to perform the same operation on each.
- Implementing stacks or queues (although more specialized data structures may be used for stacks and queues).
Example of creating and using an array in Swift:
// Creating an array of strings
var todoList: [String] = ["Buy groceries", "Pay bills", "Read a book"]
// Adding an element
todoList.append("Exercise")
// Accessing an element by index
let firstTask = todoList[0] // "Buy groceries"
// Iterating over elements
for task in todoList {
print(task)
}