swiftdictionaryhigher-order-functions

How to create custom higher order function like .maps() or .filter() works in Swift


I am just looking for the internal implementation of higher order function in swift like map, filter, reduce.

According to apple documentation.

@inlinable public func map(_ transform: (Element) throws -> T) rethrows -> [T]

Returns an array containing the results of mapping the given closure over the sequence's elements.

For e.g;

var arr = [1,2,3,4,5]

print(arr.map({$0*5}))

Output will be

[5,10,15,20,25];

or

print(arr.map({String($0)}))

I just eager to know how the computation basically works here or higher order internally works. Could you please help me here, how map works here like what to do with the values (multiply or converting into string).


Solution

  • You can create custom map like this. Under the sequence, you create your own higher order function.

    extension Sequence {
    
    public func customMap2<T>(_ transform: (Element) -> T) -> [T] {
    
        var result = [T]()
    
        for item in self {
            result.append(transform(item))
        }
    
        return result
       }
    }