R.O.S.S
R.O.S.S

Reputation: 615

Swift assignments inside conditions

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?

Upvotes: 0

Views: 234

Answers (3)

Narendra G
Narendra G

Reputation: 549

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

Upvotes: 0

rickster
rickster

Reputation: 126107

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.

Upvotes: 1

Airspeed Velocity
Airspeed Velocity

Reputation: 40955

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

Upvotes: 2

Related Questions