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

iOS Development with Swift

How to create a function in which I can print all the elements in an array in a ordered way , over and over without finishing never printing all the elemnts in an array ?

Ok, please try to clarify, I am not sure if I understand you correctly: you want to call a function that prints out all the elements of a sorted array, don't you? I do not understand that "over and over without finishing printing all elements" part. Do you want to print all elements or not? Do you want to create an infinite loop that iterates over the array from the start if it has reached the end? So many questions ;)

2 Answers

I want to create a function which print each element in an array in a ordered way but when it reached the last element i want that this function start again from the beggining printing each element.I want to do this every time that reached the last element.

Hello:

Franklin, there is a way of doing this, but I do not recommend it. Depending on what kind of computer you are running, you can run into an infinity loop that might take all the computer's resources and you will have to end up shutting it down.

With that said: DO THIS AT YOUR OWN RISK

var carFactory = ["Ford", "Lamborghini", "Ferrari"]

func printForever(yes: Bool){
    while yes {
        for cars in carFactory {
            print(cars)
        }
    }
}

// Then call the function 

printForever(true)

Again, this is not recommended. And when it comes to working with an app, I don't see a functionality on making something print non-stop. This may make your phone crash, and to be honest, I don't even think apple will allow this kind of apps in the app store.

Good luck.

Another example of what not to do ;)

extension Array where Element: Comparable {

    func sortedLoop() {
        let sorted = sort(<)

        func loopIt() {
            sorted.map { print($0) }
            loopIt()
        }
        loopIt()
    }
}

[5, 3, 1, 4, 2].sortedLoop()
["A", "C", "B", "D"].sortedLoop()