Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function inside itself

Tags:

swift

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()
}
}
like image 871
Tarjerw Avatar asked Feb 07 '23 16:02

Tarjerw


1 Answers

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.]

like image 93
matt Avatar answered Feb 16 '23 21:02

matt