Category: 01. Basic

https://cdn3d.iconscout.com/3d/premium/thumb/book-3d-icon-png-download-8786672.png

  • Swift Collection Protocols

    Swift Collection Protocols

    Arrays, Sets and Dictionaries conform to Sequence and Collection, which provide common APIs like count and isEmpty.


    Common APIs

    Use count and isEmpty to check collection size.

    Example

    let arr = [1, 2, 3]
    print(arr.count)
    print(arr.isEmpty)
    let s: Set<Int> = [1, 2, 3]
    print(s.contains(2))
    print(s.isEmpty)

    This example shows shared operations exposed via collection protocols.



    Indices

    Use the indices property to iterate valid positions.

    Example

    let arr = [10, 20, 30]
    for i in arr.indices {
      print("index: \(i), value: \(arr[i])")
    }
  • Swift Mutability

    Mutability (let vs var)

    Use let for constants and var for variables.

    Arrays and dictionaries declared with var can be modified in-place.


    Mutable vs Immutable

    Declare with var when you intend to add/remove elements; use let to prevent mutations.

    Example

    let fixed = [1, 2]
    print(fixed.count)
    var bag = [1, 2]
    bag.append(3)
    print(bag.count)


    Dictionary Mutability

    Mutate dictionaries declared with var by inserting or updating keys.

    Example

    var user = ["name": "Kai"]
    user["city"] = "Oslo"
    print(user.count)
  • Swift Sorting

    Swift Sorting

    Sort arrays with sorted() (returns new) or sort() (in-place). Provide a closure for custom order.


    Sort

    Sort ascending using sorted() and descending in-place using sort(by:).

    Example

    var nums = [3, 1, 2]
    let ascending = nums.sorted()
    print(ascending)      // [1, 2, 3]
    nums.sort(by: >)
    print(nums)           // [3, 2, 1]

    This example sorts ascending using sorted() and descending in-place using sort(by:).



    Case-Insensitive Sort

    Provide a custom closure to sort strings without regard to case.

    Example

    let names = ["bob", "Alice", "dave"]
    let caseInsensitive = names.sorted { $0.lowercased() < $1.lowercased() }
    print(caseInsensitive) // ["Alice", "bob", "dave"]
  • Swift map, filter, reduce

    Swift map, filter, reduce

    Transform and aggregate collections with mapfilter, and reduce.


    Transform and aggregate with map/filter/reduce

    Use map to transform elements, filter to select a subset, and reduce to combine into a single result.

    Example

    let nums = [1, 2, 3, 4]
    let doubled = nums.map { $0 * 2 }
    print(doubled)
    let evens = nums.filter { $0 % 2 == 0 }
    print(evens)
    let sum = nums.reduce(0, +)
    print(sum)


    Convert and Sum

    Use compactMap to convert valid strings to numbers, then reduce to sum.

    Example

    let raw = ["1", "x", "2", "3"]
    let ints = raw.compactMap { Int($0) }   // [1, 2, 3]
    let total = ints.reduce(0, +)
    print(total)

  • Swift Dictionaries

    Swift Dictionaries

    Dictionaries store key-value pairs.

    Lookups are fast by key.

    Use subscripting to read and write values.


    Basics

    Example

    var ages: [String: Int] = ["Kai": 30]
    ages["Elisabeth"] = 25
    print(ages["Kai"] ?? 0)

    This example adds and reads values using dictionary subscripting.



    Iterate Keys and Values

    Loop through a dictionary to access keys and values.

    Example

    let ages = ["Kai": 30, "Elisabeth": 25]
    for k in ages.keys.sorted() {
      print("\(k): \(ages[k]!)")
    }
  • Swift Sets

    Swift Sets

    Sets store unique values with no defined order.

    Test membership with contains, and use union/intersection operations.


    Deduplicate Values

    Use sets to deduplicate values from an array.

    Example

    var letters: Set<Character> = ["a", "b", "a"]
    print(letters.contains("a"))

    This example creates a Set which deduplicates values and checks membership.



    Set Operations

    Combine or compare sets using unionintersection and subtracting.

    Example

    let a: Set<Int> = [1, 2, 3]
    let b: Set<Int> = [3, 4]
    print(a.union(b).sorted())         // [1, 2, 3, 4]
    print(a.intersection(b).sorted())  // [3]
    print(a.subtracting(b).sorted())   // [1, 2]
  • Swift Collections

    Swift Collections

    Use arrays, dictionaries, and sets to store ordered lists, key-value pairs, and unique items.


    Arrays

    Arrays store ordered lists of values.

    Syntax: [Type] for type, append with .append, count with .count, access with array[index].

    Example

    var nums: [Int] = [1, 2, 3]
    nums.append(4)
    print(nums.count)    // 4
    print(nums[0])       // 1

    This example creates an [Int] array, appends a value, reads the count, and accesses the first element.


    Dictionaries

    Dictionaries store key-value pairs.

    Syntax: [Key: Value] for type, assign with dict[key] = value, read with dict[key] ?? default.

    Example

    var ages: [String: Int] = ["Kai": 30]
    ages["Elisabeth"] = 25
    print(ages["Kai"] ?? 0)

    This example defines a [String: Int] dictionary, inserts a key, and reads with nil-coalescing.



    Sets

    Sets store unique items.

    Syntax: Set<Element> or literal, test membership with .contains.

    Example

    var letters: Set<Character> = ["a", "b", "a"]
    print(letters.contains("a"))
  • Swift Break/Continue

    Swift Break/Continue

    Use break to exit a loop early, and continue to skip to the next iteration.


    break

    Stop the loop immediately when a condition is met.

    Example

    for i in 1...10 {
      if i == 4 { break }
      print(i)
    }

    This example stops printing when i reaches 4.



    continue

    Skip the rest of the current iteration but keep looping.

    Example

    for i in 1...5 {
      if i % 2 == 0 { continue }
      print(i) // only odd numbers
    }
  • Swift For Loop (Real-Life)

    Swift For Loop (Real-Life)

    Use loops to process arrays, paginate data, or aggregate results.


    Process arrays and aggregate results

    Loop over a collection and accumulate values to compute totals like sums or averages.

    Example

    let numbers = [1,2,3,4,5]
    var sum = 0
    for n in numbers { sum += n }
    print(sum)


    Filter Even Numbers

    Filter a collection to keep only the values you need.

    Example

    let numbers = [1,2,3,4,5]
    let evens = numbers.filter { $0 % 2 == 0 }
    print(evens)
  • Swift For-Each Loop

    Swift For-Each Loop

    Use forEach to iterate sequences with a closure.


    Iterate with forEach closures

    Pass a closure to forEach to process each element of a sequence.

    Example

    ["A","B","C"].forEach { print($0) }


    Enumerated forEach

    Use enumerated() with forEach to get index and value.

    Example

    let items = ["A","B","C"]
    items.enumerated().forEach { print("\($0.offset): \($0.element)") }