Laughter is the Best Medicine

Challenge #2: Simplify IF - ELSE statement to one line (Hint: Ternary Operator)

hey guys welcome back again for a new challenge and in this challenge we'll be looking at how do we simplify our if-else statement and that is converting our FL statement into a single line statement so I am giving you 10 seconds to figure it out so now I'm here back inside my Xcode and I'm using Swift as a programming language you can use any language which you want to use and this operator that is the operator I am talking about that is the ternary operator it is almost available in almost all of the languages so let's see how does it look like so basically we have a condition and then a question mark and then we provide in the value that is the true value that if the condition is true then this is the value and then : and then we provide in the second value that is if the condition is false then we have the second value so let's see how do we write it so now let me remove this if condition from here and simply what we I'm going to do is condition and then we put a question mark and we see print condition was true or else print condition was false so and now let me run this and as you can see it is such an easy statement to write using this statement we have converted the oilfields statement that is of five lines of code into a single line of code now if I change the value of condition to be false and I run this application again we see that the condition was false now whatever we want to assign a variable a certain value depending on the condition so it is very simple so let me declare a variable some variable equal to and then we check for the condition if the condition is true then its value would be ten else its value would be 20 now let me print this some variable and let's see what we have here since the condition is false we should have 20 here and that is what we are getting now let me change the condition to be true and let's see and we will be getting 10 for this some variable value so this is what all the ternary operator is all about and I think you should use ternary operators more often if you want to simplify your code and it will make you a better programmer so thanks guys for watching and if you liked the video to hit the like button and if you haven't subscribe to the channel do subscribe to the channel and if you want you can support me on patreon or comment provide the link in the description below so thank you bye bye data take care and have a good day

Leave a Reply

Your email address will not be published. Required fields are marked *