DEV Community

Ajithmadhan
Ajithmadhan

Posted on • Updated on

Swift - Collections

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

collections

Arrays

An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.

creating empty array

var arr:[Int] = []
Enter fullscreen mode Exit fullscreen mode

Accessing and modifying the array

  • number of elements in an array -> count method
  • to check the array is empty -> isEmpty method
  • to add new item to end -> append method (+=)
  • to retrieve a value from array using subscript syntax -> arr[0]
  • to insert at a particular location -> insert(_at:) method
  • to remove at a particular location -> remove(_at:) method
  • to remove the last element -> removeLast() method

Iterating over an array

we can iterate over the entire set of values using the for-in loop

var shoppingList = ["milk","bread","eggs"]
for item in shoppinglist {
print(item)
}
//milk
//bread
//eggs
Enter fullscreen mode Exit fullscreen mode
  • If you need the index value, use the enumerated() method to iterate over the array instead.For each item in the array, the enumerated method returns a tuple composed of an integer and an item.
for (index,value) in shoppingList.enumerated() {
print("\(index) : \(value)")
}
//0 : milk
//1 : bread
//2 : eggs
Enter fullscreen mode Exit fullscreen mode

Sets

A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items isn’t important, or when you need to ensure that an item only appears once

creating set

//Empty set
var letters = Set<Characters>()

//Using array literals
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
Enter fullscreen mode Exit fullscreen mode

Accessing and modifying set

  • Count the total items in set -> count method
  • to check the set is empty or not -> isEmpty method
  • to insert new item -> insert(_:) method
  • to remove a particular Item -> remove(_:) method

Iterating over set

You can iterate over the values in a set with a for-in loop.

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop
Enter fullscreen mode Exit fullscreen mode

Swift’s Set type doesn’t have a defined ordering. To iterate over the values of a set in a specific order, use the sorted() method, which returns the set’s elements as an array sorted using the < operator.

for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz
Enter fullscreen mode Exit fullscreen mode

Set operations

Set operations

  • Use the intersection(_:) method to create a new set with only the values common to both sets.
  • Use the symmetricDifference(_:) method to create a new set with values in either set, but not both.
  • Use the union(_:) method to create a new set with all of the values in both sets.
  • Use the subtracting(_:) method to create a new set with values not in the specified set.

Dictionary

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary.

Creating an Dictionary

var namesOfIntegers: [Int: String] = [:]
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]
Enter fullscreen mode Exit fullscreen mode

Accessing and modifying

  • Count the total items in Dictionary -> count method
  • to check the Dictionary is empty or not -> isEmpty method

You can add a new item to a dictionary with subscript syntax. Use a new key of the appropriate type as the subscript index, and assign a new value of the appropriate type:

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

Enter fullscreen mode Exit fullscreen mode

You can also use subscript syntax to change the value associated with a particular key:

airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"
Enter fullscreen mode Exit fullscreen mode

As an alternative to subscripting, use a dictionary’s updateValue(:forKey:) method to set or update the value for a particular key. Like the subscript examples above, the updateValue(:forKey:) method sets a value for a key if none exists, or updates the value if that key already exists. Unlike a subscript, however, the updateValue(_:forKey:) method returns the old value after performing an update. This enables you to check whether or not an update took place.

Iterating over dictionary

You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// LHR: London Heathrow
// YYZ: Toronto Pearson
Enter fullscreen mode Exit fullscreen mode

You can also retrieve an iterable collection of a dictionary’s keys or values by accessing its keys and values properties:

for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: LHR
// Airport code: YYZ

for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: London Heathrow
// Airport name: Toronto Pearson
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)