Sobes.tech
Junior

What is the difference between collections and arrays?

sobes.tech AI

Answer from AI

In Swift, there is no separate 'collection' type. There is a protocol Collection, which is conformed to by various types, including Array, Set, and Dictionary.

Main differences between Array and other types conforming to the Collection protocol:

  1. Order of elements:

    • Array: An ordered collection. Elements are stored in a specific order and accessible by index.
    • Set: An unordered collection of unique elements.
    • Dictionary: An unordered collection of key-value pairs.
  2. Access by index:

    • Array: Supports access to elements by integer index.
    • Set: Does not support direct access by index.
    • Dictionary: Access to values is by key.
  3. Uniqueness of elements:

    • Array: Can contain duplicate elements.
    • Set: Contains only unique elements.
    • Dictionary: Keys must be unique; values can repeat.
  4. Performance:

    • Access by index in Array is usually faster (O(1) on average).
    • Searching for an element in Set or by key in Dictionary is usually faster (O(1) on average) compared to searching in Array (O(n)).

Example of using Array:

// Creating an array of strings
var names: [String] = ["Alice", "Bob", "Charlie"]

// Accessing an element by index
let firstPerson = names[0] // "Alice"

// Adding an element
names.append("David") // ["Alice", "Bob", "Charlie", "David"]

Example of using Set:

// Creating a set of integers
var uniqueNumbers: Set<Int> = [1, 2, 3, 3, 4] // {1, 2, 3, 4} - duplicate removed

// Checking for the presence of an element
let containsThree = uniqueNumbers.contains(3) // true

Example of using Dictionary:

// Creating a dictionary of "name - age"
var ages: [String: Int] = ["Alice": 30, "Bob": 25]

// Accessing a value by key
let aliceAge = ages["Alice"] // 30

// Adding a new pair
ages["Charlie"] = 35 // ["Alice": 30, "Bob": 25, "Charlie": 35]
What is the difference between collections and… - sobes.tech