-3
func someone() -> String {
    defer {
        return "World"
    }
    return "Hello"
}

someone()

for above snippet of code its throwing error "'return' cannot transfer control out of a defer statement" so what is the reason behind it?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
Vyankatesh
  • 139
  • 1
  • 10
  • 3
    The code inside `defer` is being executed **after** any statement to leave the current scope so `return` makes no sense. – vadian Feb 07 '22 at 15:14
  • 2
    Of course, it could be *designed* to allow you to transfer control out of a defer statement. To do that, the language designers would have to think about and implement exactly what is expected to happen for each of the control transfer statements (e.g. which value should `someone` return? `World` or `Hello`?), which is more work than just completely disallowing it. And why would this be useful anyway? [See also](https://meta.stackoverflow.com/questions/293815/is-it-subjective-to-ask-about-why-something-wasnt-implemented-in-the-language/293819#293819) – Sweeper Feb 07 '22 at 15:16
  • 2
    PS: Please read the [description of the `defer` statement](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html#ID514) – vadian Feb 07 '22 at 15:21
  • Seems Swift does it's best to never be compatible with other languages' `finally` block. Rule-1: `defer` should be before the throwing line, Rule-2: know `defer` does not support `return` keyword. – Top-Master Dec 21 '22 at 15:18

1 Answers1

2
  1. Returning more than one value is not allowed, regardless of whether you try to do that in a defer statement or not.

  2. Whatever you do to mutate a return value in a defer statement, that's not accessible via a return. It happens afterward.

func someone() -> String {
  var `return` = "Hello"

  defer {
    `return` += "World"
  }

  return `return`
}

someone() // Hello