All Collections Swift5 iOS

 25. Arrays in Swift


An array is an ordered collection in Swift that stores multiple values of the same type. Arrays can be mutable (var) or immutable (let), and they maintain the order of their elements.


Creating Arrays

1. Empty Array


var emptyArray: [Int] = []

print(emptyArray) // Output: []



2. Array with Default Values


var defaultArray = Array(repeating: 0, count: 5)

print(defaultArray) // Output: [0, 0, 0, 0, 0]



3. Array with Literal Values


let fruits = ["Apple""Banana""Cherry"]

print(fruits) // Output: ["Apple", "Banana", "Cherry"]


Array Operations

1. Accessing Elements


let numbers = [102030]

print(numbers[1]) // Output: 20



2. Adding Elements


var numbers = [123]

numbers.append(4// Add a single element

numbers += [56// Add multiple elements

print(numbers)    // Output: [1, 2, 3, 4, 5, 6]



3. Removing Elements


var items = ["A""B""C"]

items.remove(at: 1// Removes "B"

print(items)        // Output: ["A", "C"]



4. Updating Elements


var scores = [506070]

scores[1] = 65

print(scores) // Output: [50, 65, 70]



5. Checking for Existence


let fruits = ["Apple""Banana""Cherry"]

print(fruits.contains("Banana")) // Output: true


Advanced Operations

1. Iterating Over an Array


let numbers = [123]

for number in numbers {

    print(number)

}

// Output:

// 1

// 2

// 3



2. Sorting an Array


let unsorted = [31415]

let sorted = unsorted.sorted()

print(sorted) // Output: [1, 1, 3, 4, 5]



3. Combining Arrays


let array1 = [12]

let array2 = [34]

let combined = array1 + array2

print(combined) // Output: [1, 2, 3, 4]


26. Sets in Swift


set is an unordered collection of unique elements in Swift. Unlike arrays, sets do not maintain element order and automatically discard duplicate values.


Creating Sets

1. Empty Set


var emptySet: Set<Int> = []

print(emptySet) // Output: []



2. Set with Values


let setSet = ["Apple""Banana""Cherry"]

print(set// Output: A random order of ["Apple", "Banana", "Cherry"]


Set Operations

1. Adding Elements


var items: Set = ["A""B"]

items.insert("C")

print(items) // Output: A random order of ["A", "B", "C"]



2. Removing Elements


var items: Set = ["A""B""C"]

items.remove("B")

print(items) // Output: A random order of ["A", "C"]



3. Checking Membership


let setSet = [123]

print(set.contains(2)) // Output: true


Set Operations (Mathematics)

1. Union


let set1: Set = [12]

let set2: Set = [23]

print(set1.union(set2)) // Output: [1, 2, 3]



2. Intersection


print(set1.intersection(set2)) // Output: [2]



3. Difference


print(set1.subtracting(set2)) // Output: [1]



4. Symmetric Difference


print(set1.symmetricDifference(set2)) // Output: [1, 3]


27. Dictionaries in Swift


dictionary is an unordered collection of key-value pairs. Each key in a dictionary must be unique, but values can be repeated.


Creating Dictionaries

1. Empty Dictionary


var emptyDict: [StringInt] = [:]

print(emptyDict) // Output: [:]



2. Dictionary with Values


let dict = ["Apple"3"Banana"2]

print(dict) // Output: ["Apple": 3, "Banana": 2]


Dictionary Operations

1. Accessing Values


print(dict["Apple"]) // Output: Optional(3)



2. Adding Key-Value Pairs


var dict = ["A"1]

dict["B"] = 2

print(dict) // Output: ["A": 1, "B": 2]



3. Removing Key-Value Pairs


dict.removeValue(forKey: "A")

print(dict) // Output: ["B": 2]



4. Iterating Through a Dictionary


for (key, value) in dict {

    print("\(key)\(value)")

}

// Output:

// A: 1

// B: 2


28. Collection Iteration


Swift provides several ways to iterate over collections like arrays, sets, and dictionaries.

1. Using for-in Loop


let array = [123]

for item in array {

    print(item)

}



2. Using enumerated()


for (index, value) in array.enumerated() {

    print("Index \(index): Value \(value)")

}



3. Iterating Over Dictionaries


let dict = ["A"1"B"2]

for (key, value) in dict {

    print("\(key)\(value)")

}


29. Transforming Collections


Swift provides higher-order functions like mapfilter, and reduce to transform and manipulate collections.


1. map


Transforms each element in a collection.


Example: Doubling Numbers


let numbers = [123]

let doubled = numbers.map { $0 * 2 }

print(doubled) // Output: [2, 4, 6]


2. filter


Filters elements based on a condition.


Example: Filtering Even Numbers


let numbers = [12345]

let evens = numbers.filter { $0 % 2 == 0 }

print(evens) // Output: [2, 4]


3. reduce


Combines elements into a single value.


Example: Summing Numbers


let numbers = [123]

let sum = numbers.reduce(0, +)

print(sum) // Output: 6


Advanced Example: Combining All Three


let numbers = [12345]

let result = numbers.filter { $0 % 2 == 0 }

                    .map { $0 * $0 }

                    .reduce(0, +)

print(result) // Output: 20


Explanation:

1. filter: Keeps even numbers.

2. map: Squares each number.

3. reduce: Sums the squares.


Comments

Popular posts from this blog

Complete iOS Developer Guide - Swift 5 by @hiren_syl |  You Must Have To Know 😎 

Debugging

Swift Fundamentals You Can’t Miss! A List by @hiren_syl