Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Closures in Swift 2 Building Standard Library Functions Using Map

I'm having difficulty with the challenge : Use the map function to iterate over the numbers array

I'm having trouble with the following question: Use the map function to iterate over the numbers array and transform the values to their string representations. Assign the resulting array to a constant named numberStrings.

I receive the error: "Make sure you call the map function on the numbers array". Here is the code I am using:

map.swift
let numbers = [1,2,3,4,5]
extension Array {
    func map<T>(transform: Element -> T) -> [T] {
        var result = [T]()
        for x in self {
            result.append(transform(x))
        }
        return result
     }
}
let numberStrings = numbers.map { String($0) }

2 Answers

Steven Deutsch
Steven Deutsch
21,046 Points

Hey Arthur Rubio,

You're overthinking the challenge! You don't have to create the map function, this is already part of the Swift Standard Library. In this course, we just practiced recreating the map method so that we could understand how it works behind the scenes :)

let numbers = [1,2,3,4,5]

let numberStrings = numbers.map {
   String($0)
}

Good Luck

SON OF A. I know that I did something to this effect before I over complicated it. I just wish I would have kept a copy of my original code to know where I went wrong. Oh well. Thank you for your help. I appreciate it.

Stephen Wall
PLUS
Stephen Wall
Courses Plus Student 27,294 Points

Swift already provides the map function for you. You just need to make a simple trailing closure for the new array:

let numbers = [1,2,3,4,5]
let numberStrings = numbers.map { String($0) }