-1

I realize this is a really simple bit of code, and I'm quite sure it's recursive, but I just want to make sure it is what I think it is. (Sorry if this is kind of a lame question, I'm just second guessing myself on if I understand what recursion actually is.)

var x = 0
func countToTen() {
    if (x <= 10) {
        println(x)
        x++
        countToTen()
    }
}
123
  • 8,733
  • 14
  • 57
  • 99

2 Answers2

5

Yes, this is definitely recursive! For good style, however, it is best to make x a parameter to the function. It's sort of a style issue, but it also makes the code easier to maintain to not have global variables like you have here.

here's what I'm talking about.

func countToTen(x) {
    if (x <= 10) {
        println(x)
        countToTen(x + 1)
    }
}

Now you can just call the function

countToTen(1)

And that would count from 1 to ten, for instance. You did it correctly, my version is just perhaps slightly cleaner form.

Dan
  • 660
  • 6
  • 15
-1

In programming, if a method:

  • Calls itself and,
  • Moves towards a base case (in this case x == 10)

then it is recursive.

Here is a post about real-world examples.

Community
  • 1
  • 1
  • Would a while loop there not just call another instance of the method? Leaving 9 methods continuously calling new methods? – DylanB Aug 07 '15 at 01:25
  • Checked it in a [fiddle](http://swiftstub.com/) turns out if and while actually give the same output in this case, which is interesting because I don't think that would happen in most other languages. – Ryan Pousson Aug 07 '15 at 01:52
  • Okay, I would have thought that a while loop would just call another instance of CountToTen 10 times, and so on which would call CountToTen something like 100000000 times? lol – DylanB Aug 07 '15 at 02:06
  • Who knows ¯\_(ツ)_/¯ I removed it anyways. – Ryan Pousson Aug 07 '15 at 02:18