iOS

iOS Lesson 07 – Constant and Logical statements in Swift

So in this knowledge bit, we are going to talk about constants and logical statements in swift. Even though we have covered how to make decisions Lets start right away with the playground.

Open up your Xcode and create a new playground. We are going to call this one “ConstantsAndAdditionalOperators” and delete the Hello world line.

Constant and Logical statements in Swift

Let:

Let is a constant in swift. It only means that once it is set, cannot be changed. Let are those variables who cannot be changed once they are assigned. Let’s start with the coding part

Code:

let canChange = false

if !canChange{

print("Cannot change it mate! ")

} 

in these lines of code we are using the let keyword to define that we are going to create a constant, then we give it a name “canChange” and then we use the equal sign “=” then a value(in this case “false”). So this is a constant and it is false that cannot be changed.  In the IF statement, the bool canChange is compared by a “logical not operator” “!”

Thing to mention:

“ !canChange is equivalent to canChange != true”, except for a little bit of writing.

You would ever want to use the constants whenever you are sure that you are not going to change the value so its very good to use constants at every possible time.

So, we are now going to use some logical operators with constants

Code:



let securityCheck = true

let scanComplete = false

let vipGuy = true

if (securityCheck && scanComplete) || vipGuy {

print("You can go duckhead!")

}   

In this example, we have created three constants and trying to compare two conditions with those three constants.

Condition#1: if the securityCheck is true AND scanComplete is true

Condition#2: if the vipGuy is true

We have put the OR operator in our if statement that means that if any of these two conditions returns true we are going to execute the print statement. We have used brackets to merge two constants in a single condition.

With these logical operators, you can use parenthesis but you really don’t need to. They are optional but sometimes they help with readability

Let Logical statement in Swift

 

Conclusion:

So in this knowledge bit, we have covered constants, conditional operators and logical statements using AND and OR operators. Similarly, you can use logical operators in the same line. we are going to use these a lot when you are making conditional logic that how we can use them efficiently in the code to make our lives easier. You can get all the code from here.

 

You can have a look at our whole IOS series as well.

 

Click to comment

Most Popular

To Top