iOS Interview - Reimplement map and compactMap high-order function in Swift

April 16, 20241 min read#swift, #ios, #interview

Question

Reimplement the map high-order function in Swift

Answer

extension Collection {
  func myMap<T>(transform: (Element) -> T) -> [T] {
    var result = [T]()
    forEach { item in
      result.append(transform(item))
    }
    return result
  }
}

print([1,2,3,4,5].myMap(transform: {$0 * 2}))

Output

[2, 4, 6, 8, 10]

Question

Reimplement the compactMap high-order function in Swift

Answer

extension Collection {
  func myCompactMap<T>(transform: (Element) -> T?) -> [T] {
    var result = [T]()
    forEach { item in
      if let newItem = transform(item) {
        result.append(newItem)
      }
    }
    return result
  }
}

print(["1","2","3","A","4","5","B"].myCompactMap(transform: { Int($0) }))

Output

[1, 2, 3, 4, 5]
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024