swiftfunctional-programming

Array.map(String.init): what happens here?


let iNumbers = [1, 2, 4, 8, 16]
let sNumbers = iNumbers.map(String.init)
print(sNumbers)

// I would expect (and understand) something like this:
let sNumbers2 = iNumbers.map { num in
    String(num)
}
print(sNumbers2)

What does String.init do? It's not even a proper method call.

Can someone give some explanation?


Solution

  • It's the same, because, map can take a function / closure as its input parameter or expose to the outside (as your sNumbers2).

    @inlinable public func map<T, E>(_ transform: (Element) throws(E) -> T) throws(E) -> [T] where E : Error
    

    So:

    iNumbers.map(String.init)
    
    //is a shorter way and equivalent to
    
    iNumbers.map { num in
        String(num)
    }
    
    //and also the same if your have any function that return a String
    func convert(_ input: Int) -> String {
        String(input)
    }
    
    iNumber.map(convert) //<- still valid ✅