Swift - Statement If Statement

Introduction

Swift supports the traditional C-style If statement construct for decision-making.

The syntax for the If statement is as follows:

if  condition {
   statement (s)
}

Here is an example of the If statement:

var raining = true  //raining is of type Boolean
if raining {
   print("Raining now")
}

In Swift, there is no need to enclose the condition within a pair of parentheses ( )

Here, raining is a Bool value, you can specify the variable name in the condition.

You can explicitly perform the comparison using a comparison operator:


if  raining == true  {
   print("Raining now")
}

In Swift, for non-Boolean variables or constants you are not allowed to specify the condition without an explicit logical comparison:

var number = 1  //number is of Int type
if number {     //this is not allowed in Swift
    print("Number is non-zero")
}

To perform the comparison, you need to explicitly specify the comparison operator:

Demo

var number = 1  //number is of Int type
if  number == 1  {
   print("Number is non-zero")
}

Result

In Swift, the following is not allowed:

var number = 1  //number is of Int type
if number = 5 { //not allowed in Swift
    print("Number is non-zero")
}

This limitation is useful in preventing unintended actions on the developer's part.

Related Topic