-4

I have a question about 'if let' statement in the context of Optionals.

Basically, I thought that if statement works like this 'if (true) { (this statement will execute) } if (false) { (this statement will not execute) }

but in the 'if let' statement, it doesn't work like above.

Here is the code:

var isDeleted: Bool?
isDeleted = false
if let deleted = isDeleted { print(deleted) }

in above code, maybe you know that 'let deleted = isDeleted' returns 'false' but, 'print(deleted)' is successfully executed Does anyone know why?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
이신우
  • 39
  • 3
  • 2
    This question and similar questions have been asked before, take a look [here](http://stackoverflow.com/questions/25828301/how-is-swift-if-let-evaluated) for example – milo526 Jan 03 '17 at 14:28
  • 2
    `if let` does not care about the *actual* value of the boolean, it only cares about wether or not the optional has a value or is `nil`. – luk2302 Jan 03 '17 at 14:29
  • @milo526 thx for your link, but I want to know base knowledge of this concept. I knew about Optional Bindings. so does optional binding override default function of 'if' statement? – 이신우 Jan 03 '17 at 14:33
  • @luk2302 thx for your reply all! – 이신우 Jan 03 '17 at 14:34
  • If you have a boolean condition wrapped in an optional, and want to conditionally proceed into a some block (say an `if` body) only if it is **1)** not `nil`, and **2)** if so, `true` valued, you needn't necessarily use optional binding, but could simply use the `nil` coalescing operator (`??`) to test the wrapped conditional or use a default value (`false`) if the optional is `nil`. E.g.: `if isDeleted ?? false { print("true!") }`. This will print `"true!"` only if `isDeleted` contains `.some(true)`. – dfrib Jan 03 '17 at 15:11

1 Answers1

2

Your first line declares an optional boolean. This has no value. The next line sets isDeleted, the optional boolean, to false.

I think what you're confused about is what the if let statement does.

Think of it as a safe let statement.

Consider this line of code:

let deleted = isDeleted

If you used this code in place of your if let statement, it would run just fine. But if you never initialized isDeleted, your app would crash.

In more advanced scenarios, you may not know if the value has been initialized, and that's where the if let comes in.

If there is no error with the let statement, then the code within the brackets will be executed, and a temporary variable (in this case "deleted") will be declared and initialized.

If there is an error, your app will not crash and the code within the brackets will not be run.

Hope this helps.

bearacuda13
  • 1,779
  • 3
  • 24
  • 32