← back to the blog


Swift Array Map method with a trailing closure

Posted on April 27th, 2020 in Swift by George

 

This an example of how to use map function with a trailing closure over an array value in Swift 5.2. 

 

let digitNames = ["Zero", "One", "Two","Three","Four","Five","Six","Seven","Eight","Nine"];

func stringify(_ numbers: Array<Int>) -> Array<String> {
    
    //Trailing closure immediatly after .map
    let stringers = numbers.map { (number) -> String in
        
        var output = "";
        var number = number;
        
        repeat {
            output = digitNames[number % 10] + output
            number /= 10
        } while number > 0
        
        return output;
    }
    
    return stringers;
}

print(stringify([25,42,22]))

Thank you and stay safe.