Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Fun Facts App - For Loop Question

Hi all,

I am modifying the Fun Facts starter app a little bit. I'd like to pass through my array every time the button is pressed.

struct WorkoutBook {
    let workoutArray = [
        "500",
        "600",
        "800",
        "300",
        "Pull"
    ]

    func doWork() -> String {
        for workout in workoutArray {
            return workout
        }
}

What is exactly what you are trying to do? Your code won't work because when you execute the return statement, the function ends and returns the value. It doesn't continue to iterate through your array.

Hey Andres, thanks for the reply. I would like to iterate through the array, how could I adjust the function to do that?

You are already iterating through the array, the question is with what purpose? Or what do you expect to return?

I would like to return the value within the 'workoutArray' array, and display that value on the screen.

1 Answer

Ok, then you need to write that code in your View Controller.

You could do this within an IBAction or in viewDidLoad. You need to have at least a label to display the array contents.

Try something like this

for workout in workoutBook.workoutArray {
   funFactLabel.text = funFactLabel.text?.stringByAppendingString(workout)
}

To have that code working, you need to have a label (funFactLabel I suppose) and you need to instantiate your WorkoutBook class like this:

let workoutBook = WorkoutBook()

You also need to add a carriage return at the end of the string or you will have your workouts displayed like this: "500800600300Pull"