-6

In Swift you can't check variables directly like this:

if testValue {
    ...
}

However, you can check it by, in fact, reassigning it like this:

let testValue: String?

if let test = testValue {
    ...
}

Why so? What is the magic under the hood??

Yehor Levchenko
  • 56
  • 1
  • 2
  • 10

2 Answers2

1

if testValue is a Bool then you can say:

if testValue {
  //Code
}

However, Swift is more strictly typed than C and other C-like languages.

In C, a pointer can be nil, which is zero, which is the same as false, so

if (aPointer) {}

is equivalent to

if (aPointer != nil)

However, Swift doesn't allow that. Pointer types can't be zero, nil is a special "no value" setting that is not the same as zero or false.

You have to explicitly say if aPointer != nil in Swift.

As others have pointed out, if let is something different, known as "optional binding". To explain that you'd need to understand Optionals.

In Swift, nil values are handled by a special wrapper known as an "Optional". Think of an Optional as a wrapped package that can either be empty or can contain an object.

An Optional either contains some value or it contains nil. To get at the value inside you have to "unwrap" the Optional.

There is a "force wrap" (!) expression that says "Trust me, I know this Optional can never be nil." If you use it and the Optional does contain nil, your program crashes. Thus I call it the "crash if nil" operator, and suggest you avoid it unless you really know what you're doing.

Then there is "if let" optional binding. In the following code:

var value: String?

if let testValue = value {
    //test value only exists inside these braces.
    print(value)
} else {
    //testValue is not defined here
    print("value is nil")
}
//testValue isn't defined here either.

The if let says "if the Optional variable value contains a non-nil value, remove the value from the Optional and put it into a non-Optional let constant called testValue, that will only be defined inside the braces that follow the if statement.

There are also other ways of dealing with Optionals like guard statements and the "nil coalescing operator" but I'll leave it to you to research those. I'm not going to cover every aspect of Opionals in a short forum post.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

Conditional binding if let/for let/while let is a special form that's baked into the language. The let test = testValue part isn't the same as the statement that it would usually be parsed as. It has special, different, meaning when prefixed with if/for/while.

Alexander
  • 59,041
  • 12
  • 98
  • 151