-3
let e: String? = "novel"
guard let f = e
else { return }
print(f)

i got error like below if I code like above

Playground execution failed:

error: dotinstall.playground:175:12: error: return invalid outside of a func
else { return }

I wanna use "guard let syntax " without "func()"

I tried it in some ways, but its wasn't worked well.I know almost the "guard let syntax " usually used with "func()". But if I try it with "if let syntax " it was worked without error like below

let S: String? = "jjjj"
if let Thailand = S {
    print(Thailand)}

please show me how can I code with "guard let" without "func()"

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
revoiot
  • 61
  • 1
  • 1
  • 7
  • You can use `fatalError()`, use anything that doesn't continue, use something like `break`, `return`, `continue`, `fatalError()`, or anything that returns `Never`, etc... – user9335240 Feb 21 '18 at 14:23
  • This error caused by ```return``` statement. This error is not related ```guard let``` – Emre Ozdil Feb 21 '18 at 14:29
  • See [`guard vs if-let`](https://stackoverflow.com/a/39263210/5175709). Scroll down to *Guard requires scope exiting* – mfaani Feb 21 '18 at 14:57

1 Answers1

4

Try this in playground:

guard let f = e else { fatalError("s is nil") }

Hope it helps!

Agent Smith
  • 2,873
  • 17
  • 32