Sorry, but your solution is not 100% correct. The return type is wrong. If someone calls let arr = ["Hello", "World", "lets go"] print(map(arr) { $0.count }) your solution will throw an error. The correct solution would be: func map(_ elements: [T], _ transform: (T) -> U) -> [U] { var results = [U]() for element in elements { results.append(transform(element)) } return results }
By the way map not always return same as input type. Transform can decide output type. so type U also may required.
thanks !! clear explanation. A better solution could have been by creating an extension on Collection, so that it can be used like Swift map function
Sorry, but your solution is not 100% correct. The return type is wrong. If someone calls
let arr = ["Hello", "World", "lets go"]
print(map(arr) { $0.count })
your solution will throw an error.
The correct solution would be:
func map(_ elements: [T], _ transform: (T) -> U) -> [U] {
var results = [U]()
for element in elements {
results.append(transform(element))
}
return results
}