Swift assignments inside conditions

226 views Asked by At

I was wondering what this code does:

var something: String = "Hi"

if something = "Hello world!" {
    // Will this be executed?
}

Will it assign to something variable and do the if body? Or will it set the value of that variable only for the if body and outside it will not change? Or has it anything to do with nil?

3

There are 3 answers

0
rickster On BEST ANSWER

This pattern only works for assignments that can fail — that is, if you're assigning the result of an expression that returns an Optional value. And in that case, you use if let, not just if.

2
Airspeed Velocity On

Assignments are not expressions that return booleans, so cannot be used inside an if like this. So this won’t compile.

(though you will get a misleading compiler message)

assignment in if failing to compile

0
Narendra G On

we can't use assignment operator for if condition, you would you if let suppose if you are working with optional types

Here are some operators that helps you get clarity to differentiate from assignment operator

=   assignment operator
==  is equal to
=== is identical to