Tarjerw
Tarjerw

Reputation: 525

Calling a function inside itself

I have a function, and in some cases I want it to be used two times in a row, is there a way to call the function inside itself

something like, my function is a lot longer and being abel to do something like this would save a lot of time

func theFunc() {
count++ 
if count < 4 {
thFunc()
}
}

Upvotes: 4

Views: 2757

Answers (1)

matt
matt

Reputation: 534885

That's called recursion, and it's perfectly legal:

var count = 0
func theFunc() {
    print(count)
    count += 1
    if count < 4 {
        theFunc()
    }
}
theFunc() // 0 1 2 3

The only trick is not to recurse too deeply, as you risk running out of resources, and don't forget to put some sort of "stopper" (such as your if count < 4), lest you recurse forever, resulting in (oh the irony) a stack overflow.

[Extra for experts: there are some languages, such as LISP, that are optimized for recursion, and where recursion is actually preferred to looping! But Swift is not really one of those.]

Upvotes: 11

Related Questions