There are multiple interesting questions here about attempting to define recursive closures in Swift. I think the one with the clearest answers is this post asking the question of why one can't declare and define a recursive closure in the same line in Swift. However, they don't ask the reverse question. That is, if I can't create code like this:
var countdown = { i in
print(i)
if i > 1 {
countdown(i - 1)
}
}
// error: Variable used within its own initial value
Then why am I allowed to write code like this:
func countdown(_ i: Int) {
print(i)
if i > 1 {
countdown(i - 1)
}
}
What's so special about functions that makes them not have any issues when trying to call themselves within their own declaration? I understand the issue behind the closure: it's trying to capture a value (the closure itself) that doesn't yet exist. However, what I don't understand is why the function doesn't have the same problem. Looking at the Swift Book, we see that:
Global functions are closures that have a name and don’t capture any values.
Which is a half-answer: the function above doesn't cause issues because functions don't capture values. But then, how do functions do their work if they don't capture values (particularly recursive ones)?