4 ms·
Huh, I didn't know about `return` in `defer`, but is it really useful?
by mojuba 9mo ago
Huh, I didn't know about `return` in `defer`, but is it really useful?
- deleted 9mo ago[deleted]
- ninkendo 9mo agoNo, I actually misremembered… you can’t return in a defer. The magical thing I was misremembering is that you can reference a not-yet-defined value in a defer, so long as all code paths define it once: fn callFoo() -> FooResult { let fooParam: Int // declared, not defined yet defer { // fooParam must get defined by the end of the function foo(fooParam) otherStuffAfterFoo() // … } // all code paths must assign fooParam if cond { fooParam = 0 } else { fooParam = 1 return // early return! } doOtherStuff() } Blame it on it being years since I’ve coded in swift, my memory is fuzzy.