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]