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()
}
}
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.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With