Author: saqibkhan

  • Multidimensional

    Swift Arrays: Multidimensional

    Use nested arrays to represent 2D (or higher) structures such as matrices and grids.


    2D Arrays

    Store rows as arrays inside an outer array, then index as grid[row][col] to access items.

    Example

    var grid = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ]
    print(grid[0][1]) // 2
    for row in grid {
      print(row)
    }


    Update a Cell

    Change a value by indexing into the specific row and column.

    Example

    var grid = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ]
    grid[1][1] = 99
    print(grid[1])      // [4, 99, 6]
    print(grid[1][1])   // 99
  • Indices & Bounds

    Swift Arrays: Indices & Bounds

    Arrays have startIndex and endIndex (one past last).

    Use indices to loop valid positions.

    Out-of-bounds access crashes at runtime.


    Valid Indices

    Use indices to visit only valid positions.

    Example

    let items = [10, 20, 30]
    print(items.startIndex)       // 0
    for i in items.indices {
      print("index: \(i), value: \(items[i])")
    }

    Valid subscript indices: 0..<items.count (zero up to, not including, count).

    Example

    let items = [10, 20, 30]
    print(items[0])   // OK
    // print(items[3]) // out of bounds

    Use indices for index-and-value access without enumerated().

    Note: endIndex is not a valid subscript. The last valid index is items.index(before: items.endIndex).



    Last Valid Index

    Get the last valid index with index(before: endIndex).

    Example

    let items = [10, 20, 30]
    let lastIndex = items.index(before: items.endIndex)
    print(lastIndex)        // 2
    print(items[lastIndex]) // 30
  • Slices

    Swift Arrays: Slices

    Use ranges to create slices of arrays.

    A range is a half-open interval, meaning it includes the lower bound but excludes the upper bound.

    A slice is a view of an array that shares storage with the base array, meaning it is a reference to a portion of the array.

    When you modify a slice, the base array is also modified.


    ArraySlice

    Create an ArraySlice with a range on an array.

    Convert to Array if you need its own storage.

    Example

    let nums = [10, 20, 30, 40, 50]
    let middle = nums[1...3]          // ArraySlice<Int>
    print(middle)                     // [20, 30, 40]
    let copy = Array(middle)          // Array<Int>
    print(copy)

    Use a half-open range to exclude the upper bound:

    Example

    let nums = [10, 20, 30, 40, 50]
    let slice = nums[1..<3]   // indices 1 and 2
    print(slice)               // [20, 30]

    Slices share storage with the base array until you copy.

    Tip: Slices keep original indices.

    Convert to Array for zero-based indices.



    One-Sided Slices

    Use one-sided ranges to slice from the start or to the end.

    Example

    let arr = [0, 1, 2, 3, 4]
    print(arr[...2])  // first three elements (0...2)
    print(arr[2...])  // from index 2 to the end
  • Loop

    Swift Arrays: Loop

    Use for-in to loop values.

    Use enumerated() for index and value.


    Loop Elements

    Loop values with for-in, or use enumerated() for index and value.

    Example

    let fruits = ["Apple", "Banana", "Cherry"]
    for fruit in fruits {
      print(fruit)
    }
    for (i, fruit) in fruits.enumerated() {
      print("\(i): \(fruit)")
    }

    Get index and value with enumerated().



    forEach

    Use forEach for a functional style loop. It reads values but cannot use break/continue.

    Example

    let fruits = ["Apple", "Banana", "Cherry"]
    fruits.forEach { print($0) }
    fruits.enumerated().forEach { print("\($0.offset): \($0.element)") }
  • Swift Arrays

    Swift Arrays

    Arrays store ordered collections of values of the same type.

    Arrays are value types and copy on write.


    Create and Access

    Create arrays with literals or initializers.

    Access elements by index and use properties like count and isEmpty.

    Example

    var numbers = [10, 20, 30]
    print(numbers[0])         // 10
    numbers.append(40)
    print(numbers.count)      // 4
    print(numbers.isEmpty)    // false

    This example creates an array, accesses items, appends, and inspects properties.

    Tip: Arrays are value types.

    Mutating a copy will not affect the original (copy-on-write semantics).



    Insert and Remove

    Modify arrays by inserting and removing elements.

    Example

    var items = ["A", "B", "C"]
    items.insert("X", at: 1)
    print(items)
    items.remove(at: 2)
    print(items)
  • Unicode & Scalars

    Swift strings are Unicode-correct.

    A single character can be composed of multiple Unicode scalars.

    Visually identical strings can compare equal.


    Composed Characters

    Some characters are made from multiple Unicode scalars; Swift treats them as a single character for comparison and length.

    Example

    let e1 = "é"
    let e2 = "e\u{301}"   // e + COMBINING ACUTE ACCENT
    print(e1 == e2)
    print(e2)

    This example shows that a precomposed character and a composed sequence are considered equal in Swift.



    Unicode Scalars

    Inspect the underlying Unicode scalar values with the unicodeScalars view.

    The unicodeScalars view yields values of type UnicodeScalar.

    Example

    let s = "e\u{301}"
    for scalar in s.unicodeScalars {
      print(scalar.value)   // 101, 769
    }
  • Swift Strings: Special Characters

    Use escape sequences inside strings: \n (newline), \t (tab), \" (quote), \\ (backslash).


    Escapes

    Escape special characters with backslashes to represent newlines, tabs, quotes, or backslashes themselves.

    Example

    print("Hello\nSwift")
    print("A\tB\tC")
    print("\"quoted\"")
    print("\\")


    Multiline Strings

    Use triple quotes """ for multiline string literals. Indentation before closing quotes is ignored.

    Example

    let poem = """
    Roses are red,
    Violets are blue.
    """
    print(poem)
  • Numbers and Strings

    Swift Strings: Numbers and Strings

    Use string interpolation to mix numbers with text.

    Convert numbers to strings explicitly with String(value) when concatenating.


    Mix Text and Numbers

    Use interpolation to embed numbers directly in strings, or convert numbers with String(value) when concatenating.

    Example

    let age = 5
    print("Age: \(age)")          // interpolation
    let text = "You are " + String(age)
    print(text)
    let pi = 3.14
    print("pi = \(pi)")

    This example shows interpolation and explicit conversion with String().



    Convert String to Number

    Use numeric initializers like Int("123") which return optionals because conversion can fail.

    Example

    let s1 = "123"
    let n1 = Int(s1)           // Int?
    print(n1 ?? 0)
    
    let s2 = "abc"
    let n2 = Int(s2)           // nil (not a number)
    print(n2 == nil)
  • Swift Strings: Concatenation

    Join strings with +, or use interpolation to insert values into a string.


    Concatenate vs Interpolate

    Use + to make a new string. Use interpolation to insert values inline.

    Example

    let first = "Hello"
    let second = "Swift"
    // Concatenation
    print(first + " " + second)
    // Interpolation
    print("\(first), \(second)!")

    Interpolation is often clearer when mixing text and values.



    Append Strings

    Use += to append to a mutable string.

    Example

    var s = "Hello"
    s += ", Swift"
    print(s)
  • Swift Strings

    Strings are text. Use + to join, interpolation with \(value) to insert values, and properties like count and isEmpty to inspect them.


    Basics

    Create, combine, and inspect strings with concatenation, interpolation, and common properties.

    Example

    let s1 = "Hello"
    let s2 = "Swift"
    print(s1 + " " + s2)
    print("\(s1), \(s2)!")
    let word = "Swift"
    print(word.count)
    print(s1.isEmpty)

    This example shows concatenation, interpolation, count, and isEmpty.



    Substring and Case

    Get substrings with indices. Uppercased/lowercased creates new strings without changing the original.

    Example

    let text = "Swift"
    let start = text.startIndex
    let end = text.index(start, offsetBy: 3)
    let sub = text[start..<end]  // "Swi"
    print(sub)
    print(text.uppercased())