Learn Swift Ternary Conditional Operator (With Examples)

A standard if/else statement can get pretty lengthy – at least 5 lines of code. Many developers prefer to keep their code as concise as possible and favor a shorter syntax. Swift allows us to minimize our if/else statements with a tool called the ternary conditional operator.

The ternary conditional operator, denoted by a ?, offers a shorter, more concise alternative to a standard if/else statement. It executes one of two expressions depending on the boolean result of the condition.

A ternary conditional consists of three parts in the following format:

A \ ? \ B \ : C
  • A is the condition to check for
  • B is the expression to use if the condition is true
  • C is the expression to use if the condition is false

Suppose we’d like to check if an order was placed successfully by a customer and print them a message. We can set up the following if/else statement:

var orderSuccessfullyPlaced = false

if orderSuccessfullyPlaced {
print("Your order was received.")
} else {
print("Something went wrong.")
}

Since the value of our condition is false, the second code block executes and Something went wrong. will print.

With a sprinkle of ternary magic, we can transform our code into one line, a one liner, and achieve the same result:

orderSuccessfullyPlaced ? 
print("Your order was received.") : 
print("Something went wrong.")

Note that although the ternary conditional operator helps us develop shorter code, overusing this syntax can also result in your code being difficult to read. So, use it sparingly!

Learn Swift Programming Conditional Operator

Introduction to Swift Conditionals

On a daily basis, we’re faced with making decisions based on certain conditions; if the weather is beautiful, we’ll go for a walk, or if it’s rainy, we’ll stay in and code!

In Swift, the ability to determine an outcome based on a given condition also exists. It’s known as a conditional.

Conditionals are powerful programming tools that introduce flexibility and complex behavior to a program by allowing it to react to change. Their power comes from being the root of all decision making within an application.

Your computer, for example, contains authentication processes whose logic is handled by conditionals. If you are logged out, access to certain pages on your device may be restricted, or if your are logged in, access will be granted.

In this lesson, we’ll set up our own rules and conditions for programs to follow using Swift’s conditional statements and operators.

Swift If Statement

The if statement is the most basic and fundamental type of conditional in Swift. It is used to execute some code when a given condition is true.

The structure of an if statement is:

if condition {
this code will run if condition is true
}

 

      • The if keyword is followed by a condition whose value must be true or false.
      • The condition is immediately followed by a code block.
      • code block is a snippet of code enclosed in a pair of curly braces, { }.
      • The code block is executed only when the condition is true.
      • If the condition is false, the code block does not run.

Suppose we’re creating an app that includes an authentication process. We’d declare the variable, isLoggedIn to be true and set up the following if statement that prints a message to users who are logged in:

var isLoggedIn = true if isLoggedIn { print(“Welcome back!”) }

Since the value of the condition is true, the message, Welcome back! will get printed. If isLoggedIn was false, thus our condition false, the code block wouldn’t execute and nothing would get printed.

 

Swift  Else Statement

A tool most commonly used together with an if statement is the else statement.

An else statement is used to execute a block of code when the condition of an if statement is false. Think of the else to be synonymous with the word, otherwise. Do this if a condition is true, otherwise, do something else:

if condition {
   this code will run if condition is true
} else {
   this code will run if condition is false 
}

Two rules to remember:

  • An else statement must be used in conjunction with an if statement and cannot stand on its own.
  • An else statement does not accept a condition and is immediately followed by a code block.

In the previous exercise, we created an if statement that prints a friendly message to logged in users. Let’s use an else statement to complete this logic and print a message to users who are not logged in:

var isLoggedIn = false
if isLoggedIn {
print("Welcome back!") 
} else {
print("Access Denied.") 
}
// Prints: Access Denied.

Since the value of isLoggedIn is false, our condition is therefore, false, and the code block following the else will execute.

Swift  Comparison Operators

So far, our conditions have consisted of a single variable whose value is a Boolean, true or false. With the help of operators, we can expand on this and create conditions that utilize multiple values to achieve a Boolean result.

In this exercise, we’ll learn about one particular group of operators in Swift known as comparison operators. Comparison operators determine the relationship between two operands and return a Boolean value as a result.

Swift supports the following comparison operators:

  • == Equal to
  • != Not Equal to
  • > Greater than
  • < Less than
  • >= Greater than or equal to
  • <= Less than or equal to

Comparison operators are most commonly used to compare numerical values such as Integers and Doubles, though == and != can also be used to compare String values.

4 < 5 // true
0.5 > 0.1 // true
3.5 <= 3.0 // false
12 >= 15 // false
"A" == "A" // true
"B" != "b" // true

Notice how a capital "B" is not equal to a lowercase "b" since Swift is a case sensitive language.

Combining our knowledge of if/else statements and comparison operators, we can construct the following conditional to check for a student’s grade on an exam:

let grade = 95
if grade > 65 {
print("You passed!") 
} else {
print("You failed.")
}

Since the student’s grade is greater than 65, the first code block gets executed and prints, You passed! 🎉.

Swift Else If Statements

Until now, we’ve been working with conditionals that can handle only one condition. If that condition is met, our program follows one course of action, otherwise it follows another.

Swift provides us with a tool called the else if statement which allows us to add additional conditions to a standard if/else statement.

Here’s how it works:

if condition1 {
  this code runs when condition1 is true 
} else if condition2 {
  this code runs when condition2 is true 
} else if condition3 {
  this code runs when condition3 is true 
} else {
  this code runs when all previous conditions are false 
}
  • Similarly to an if statement, an else if statement accepts a condition and a code block to execute for when that condition is true.

  • The else if statement exists only between an if and an else and cannot stand on its own like the if statement can.

  • Any number of else if statements can exist between an if and an else.

Working off the previous example, assume we’d like to update the grading scale in a school to use the academic grading scale used in the U.S..

We can translate numerical grades to letter grades, "A""B""C", etc. with the help of multiple else if statements:

let grade = 85
let letterGrade: String
if grade >= 90 {
letterGrade = "A"
} else if grade >= 80 {
letterGrade = "B"
} else if grade >= 70 {
letterGrade = "C"
} else if grade >= 60 {
letterGrade = "D"
} else if grade < 60 {
letterGrade = "F"
} else {
letterGrade = "N/A"
}
print(letterGrade) 
// Prints: B

Since a student’s numerical grade is 85, the first else if statement executes, and the value of letterGrade becomes "B"

Swift  Ternary Conditional Operator

A standard if/else statement can get pretty lengthy – at least 5 lines of code. Many developers prefer to keep their code as concise as possible and favor a shorter syntax. Swift allows us to minimize our if/else statements with a tool called the Swift ternary conditional operator.

The ternary conditional operator, denoted by a ?, offers a shorter, more concise alternative to a standard if/else statement. It executes one of two expressions depending on the boolean result of the condition.

A ternary conditional consists of three parts in the following format:

A \ ? \ B \ : C
  • A is the condition to check for
  • B is the expression to use if the condition is true
  • C is the expression to use if the condition is false

Suppose we’d like to check if an order was placed successfully by a customer and print them a message. We can set up the following if/else statement:

var orderSuccessfullyPlaced = false

if orderSuccessfullyPlaced {
print("Your order was received.")
} else {
print("Something went wrong.")
}

Since the value of our condition is false, the second code block executes and Something went wrong. will print.

With a sprinkle of ternary magic, we can transform our code into one line, a one liner, and achieve the same result:

orderSuccessfullyPlaced ? 
print("Your order was received.") : 
print("Something went wrong.")

Note that although the ternary conditional operator helps us develop shorter code, overusing this syntax can also result in your code being difficult to read. So, use it sparingly!

>> swift ternary operator

Swift Switch Statement

Another type of conditional statement that exists in Swift is the switch statement. The switch statement is a popular programming tool used to check the value of a given expression against multiple cases. The switch statement is a lot more powerful in Swift than it is in other programming languages, thus we’ll be dedicating the next few exercises to explore its features.

Unlike the if statement, a switch statement does not check for the value of a condition and instead finds and matches a case to a given expression.

Let’s take a look at an example where a switch statement can be used. The code below uses multiple else if statements within an if/else to match a landmark to a given city:

var city = "Rome"

if city == "Rapa Nui" { 
print("Moai 🗿")
} else if city == "New York" {
print("Statue of Liberty 🗽")
} else if city == "Rome" {
print("Colosseum 🏛")
} else {
print("A famous landmark is the Eiffel Tower!")
}

Since this code involves a series of else if comparisons, it’s the perfect candidate for a switch statement rewrite:

switch city {
case "Rapa Nui":
print("Moai 🗿")
case "New York": 
print("Statue of Liberty 🗽")
case "Rome":
print("Colosseum 🏛")
default: 
print("A famous landmark is the Eiffel Tower!")
}

Notice how…

  • Our new conditional begins with the switch keyword and is followed by the variable, city which acts as the expression. The value of the expression, originally "Rome", is checked against each case within the switch block.

  • The corresponding code to execute for a case is followed by a colon, :.

  • Once the value has been matched with a case, the code for that case is executed and the switch completes its checking.

  • Very much similar to an else statement, if a matching value isn’t found, the default statement gets evaluated.

 

Swift  Switch Statement: Interval Matching

One super power that the switch statement possesses, is its ability to match values to an expression that exist within intervals. An interval denotes a range used for checking whether a given value lies within that range.

In Swift, a range is indicated by three consecutive dots, ..., also known as the closed range operator. The closed range operator signifies an inclusive range where the first and last values are included in the sequence.

Let’s see these new concepts in action. In the example below, the switch statement determines the value of year and checks which century it belongs to.

 

var year = 1943
switch year {
case 1701...1800:
print("18th century") 
case 1801...1900:
print("19th century")
case 1901...2000: 
print("20th century")
case 2001...2100: 
print("21st century")
default: 
print("You're a time traveler!")
} 
// Prints: 20th century

 

Since the year, 1943, falls between the interval, 1901...2000, the code for the third case is executed and the message, 20th century gets printed.

Fun fact: The first electronic computer was built in 1943! 💻

Swift Switch Statement: Compound Cases

Another noteworthy ability of the switch statement is its use of multiple values in a single case. These are known as compound cases. The switch statement will match each value within a compound case to the given expression.

The following code checks the value of country and determines the continent on which it is located using a switch statement. Since a continent may consist of multiple countries, compound cases deem useful:

var country = "India"
switch country {
case "USA", "Mexico", "Canada":
print("\(country) is in North America. 🌏")
case "South Africa", "Nigeria", "Kenya":
print("\(country) is in Africa. 🌍")
case "Bangladesh", "China", "India":
print("\(country) is in Asia. 🌏")
default: 
print("This country is somewhere in the world!")
} 
// Prints: India is in Asia. 🌏

Notice how…

  • The multiple values or items in a compound case are separated by a comma.
  • We used string interpolation to output the value of country within the String of the print() statement.

Swift Switch Statement: where Clause

Another neat feature available for the cases of a switch statement is the where clause.

The where clause allows for additional pattern matching for a given expression. It can also be used with loops and other conditionals such as if statements.

Assume we’re creating a program that determines if a random integer between 0 and 10 is even or odd. We can write the following program:

let randomNumber = Int.random(in: 0...10)

switch randomNumber {
case let x where x % 2 == 0:
print("\(randomNumber) is even")
case let x where x % 2 == 1:
print("\(randomNumber) is odd")
default:
print("Invalid")
}

Let’s dive into what’s happening on the first line:

let randomNumber = Int.random(in: 0...10)
  • We’re generating a random integer, Int, using the built in Swift method, .random() which returns an arbitrary value from a range of numbers. Notice how we’re using the closed range operator, ..., to denote a numerical range.

  • We then assign the randomly generated value to randomNumber. We’ll be working more with .random() in the following lessons.

Following the variable declaration is a standard switch statement that checks the value of randomNumber:

switch randomNumber {
case let x where x % 2 == 0:
print("\(randomNumber) is even")
case let x where x % 2 == 1:
print("\(randomNumber) is odd")
default:
print("Invalid")
}

// Prints: 7 is odd
  • Each case contains a variable declaration followed by a where clause and a condition. When a condition is true, the code for that case will execute.

  • The let keyword followed by the x creates a temporary binding to the randomNumber value. This means that the value of x temporarily becomes the value of randomNumber. If randomNumber is 5, then x is 5!

  • The let keyword is specifically used here instead of var since the value of x will not be reassigned at any point throughout the switch statement, thus it’s value always constant. If var is used, Swift will display a compiler warning recommending us to use let instead:

Numbers.swift:6:12: warning: variable 'x' was never mutated; consider changing to 'let' constant

Note: a compiler warning is not an error. Your program should still run even with a warning.

  • Lastly, the where condition checks if x is divisible by 2 with or without a remainder and determines if the randomNumber is even or odd.

If you run this code, chances are your output will be different from ours since the number generated each time is random!

>>  Best Django Hosting 2020

Swift conditional Review

Excellent work! In this lesson, we’ve learned the following concepts:

  • An if statement consists of a condition and code block that executes when the condition is true.
  • An else statement is immediately followed by a code block that executes when all previous conditions were false.
  • code block is denoted by a set of curly braces {}.
  • Multiple else if statements can be chained within an if/else to provide additional conditions.
  • Comparison operators include <><=>===, and != and are used to compare the values of two operands.
  • switch statement looks for the value of a case that matches the value of an expression.
  • switch statement can have cases that contain multiple items known as compound cases.
  • switch statement’s case can include a range of values using the closed range operator (...).

You’ve covered a major fundamental programming concept used in every program to control the logical flow. Feel free to utilize the empty Review.swift file and output terminal on the right to hone your understanding of conditionals and practice writing Swift code.

More Articles:

>> 5 Best Blockchain Books 2020

Best 5 Blockchain Books – You Need To Read in 2020

Best 5 Blockchain Books – You Need To read in 2020

Blockchain

What You’ll Learn & Who This Book Is For

Mastering Bitcoin is your guide through the seemingly complex world of bitcoin, providing the knowledge 
you need to participate in the internet of money. Whether you're building the next killer app, 
investing in a startup, 
or simply curious about the technology, this revised and expanded second edition provides 
essential detail to get you started.
Bitcoin, the first successful decentralized digital currency, is still in its 
early stages and yet it's already spawned 
a multi billion dollar global economy. This economy is open to anyone with the knowledge 
and passion to participate. 
Mastering Bitcoin provides the knowledge. You simply supply the passion.


The second edition includes:
A broad introduction to bitcoin ideal for non technical users, investors, and business executives
An explanation of the technical foundations of bitcoin and cryptographic currencies for developers, 
engineers, and software and systems architects
Details of the bitcoin decentralized network, peer to peer architecture, 
transaction lifecycle, and security principles
New developments such as Segregated Witness, Payment Channels, and Lightning Network
Improved explanations of keys, addresses and wallets
User stories, analogies, examples, and code snippets illustrating key technical concepts
What You’ll Learn

Explore the Blockchain ecosystem is and the different consensus mechanisms
Create miners, wallets, transactions, distributed networks and DApps
Review the main features of Bitcoin: Ethereum, NEO and EOS, and Hyperledger are
Interact with popular node clients as well as implementing your own Blockchain
Publish and test your projects for security and scalability

Who This Book Is For

Developers, architects and engineers who are interested in learning about Blockchain or implementing 
Blockchain into a new greenfield project or integrating Blockchain into a 
brownfield project. Technical entrepreneurs, technical investors or even executives 
who want to better understand Blockchain technology and its potential.
What you will learn

Master the theoretical and technical foundations of the blockchain technology
Understand the concept of decentralization, its impact, and its relationship with blockchain technology
Master how cryptography is used to secure data - with practical examples
Grasp the inner workings of blockchain and the mechanisms behind bitcoin and alternative cryptocurrencies
Understand the theoretical foundations of smart contracts
Learn how Ethereum blockchain works and how to develop decentralized applications using Solidity and relevant 
development frameworks
Identify and examine applications of the blockchain technology - beyond currencies
Investigate alternative blockchain solutions including Hyperledger, Corda, and many more
Explore research topics and the future scope of blockchain technology

Who This Book Is For

This book will appeal to those who wish to build fast, highly secure, transactional applications. 
It targets people who are familiar with the concept of blockchain and are comfortable with a programming language.
This book covers the following concepts:

Blockchain Fundamentals: From origins to the modern computing stack
The Technology Behind Blockchain: Web 3 and the economy
Bitcoin and Crypto-assets: CryptoKitties and ERC20 Tokens
Ethereum and Smart Contracts: Tutorials, Virtual machines, and autonomous organizations
Project Management and Use Cases: Lean prototyping methods and corporate Dapps
The Future of Blockchain: Quantum-resistant blockchains, AI/ML, and society
What You'll Learn

What the blockchain is
Why it is needed and what problem it solves
Why there is so much excitement about the blockchain and its potential
Major components and their purpose
How various components of the blockchain work and interact
Limitations, why they exist, and what has been done to overcome them
Major application scenarios

Who This Book Is For

Everyone who wants to get a general idea of what blockchain technology is, how it works, and how it will potentially 
change the financial system as we know it

What is Hashing in Blockchains

1. What is Hashing?

Hashing is the process of taking the input string of any length and turning it into cryptographic fixed output. Hashing is not an “encryption” we cant retrieve the original data by decrypting the hash, it’s a one-way cryptographic function. Do you know we can keep the whole data which is present on the internet in the fixed string length with the help of Hashing Algorithm. We use a mathematical algorithm called SHA-256 (Secure Hashing Algorithm -256 bits). SHA 256 is the successor of the SHA-1 which is of 160 bits.

2. How Hashing is used in Blockchain?

In Blockchain, every block has a hash of the previous block, the previous block is called as parent block for the present block and now consider a parent block has a present block and it will have a hash of previous block i.e parent block. In the blockchain, every block has a hash of the previous block. When we change any data in the present block the hash of the block will be changed, this will affect the previous block because it has the address of the previous block. For example, If we have only two blocks, one will be present block and one will be the parent block. The present block will be having the address of the parent block. If we need to change the data in the present block, we also need to change the parent block. It will be easy to change the data when there are only two blocks, but now when we come into reality in blockchain, there are 614272 blocks have been mined by 2020-01-24 12:32, and hash of 614272(th) block is 00000000000000000007a6be31011560f1e3abe8f125e356a31db6051753334e. If we want to change data in present block i.e 614272(th) block, the hash address of 614271 blocks have to be changed, but it is not possible to change the hashes of 614271 blocks, so this is how blockchain is called immutable and trustworthy of the data. The first block of a blockchain, known as a Genesis block. You can see how many blocks are mined until now at Blockchain. I have created a Visualization of this process.

If we do a small change to any part of the input there will be a huge change to the output, see the examples below for more understanding. Hashing is of the core fundamentals and foremost aspects of the immutable and defining potential of blockchain technology. It preserves the authenticity of the data that is recorded and viewed, and as such, the integrity of a blockchain as a whole. It is one of the more technical aspects of the technology, however, understanding it is a solid step in understanding how blockchain functions and the immeasurable potential and value that it has.

3. How do Merkle trees work?

When there is a large body of data it will be hard to verify it and takes a lot of memory to store and secure it but with the help of Merkle tree, we can easily overcome all these problems. Merkle tree is a fundamental part of the Blockchain Technology, it is in a structure where we can easily find out any change happens to a large amount of data and verifications of the data can be done efficiently. These are used by both Bitcoin and Ethereum.

As we can see in the above image, all the transactions are at the bottom and the top single hash is called Root hash or Merkle root. Let us consider one example, there are 4 transactions with A, B, C, D. Now A and B hash will combine to form one hash and C and D another hash, AB hash and CD hash now combine to form one single hash called Root hash or Merkle Root ABCD. The Root hash will have all the information of all the transactions. Merkle tree will repeatedly hash, pair of nodes till there is only one hash left called Root Hash. Merkle tree is a binary tree, so need to have even number of leaf nodes, if the number of transactions is odd, the last hash will be duplicated once to create an even number of leaf nodes…

In the above image we can see the duplicate transaction hashing when their is an odd number of transactions, this is how merkle tree will duplicate for odd number of leafs. All the data of the Transactions are summarized into single Root hash and that is stored in the block header, As we now any change in the data the whole hash function we will changes, if hash changes, so do Merkle root changes. Merkle tree helps us to maintain the integrity of the data. Another advantage of Merkle tree is if you want to know the status of one particular transaction, we don’t need to download the entire blockchain, we just need to ask for vertical proof and ask for a certain branch of a tree and verify one particular transaction branch.

4. How can we Secure Data with Hashing?

Hashing drastically increases the security of the data. There is no way to decrypting the data because we are not encrypting it. As I mentioned already it’s a one-way cryptographic function. A cryptographic hash function needs to have several crucial qualities to be considered useful, these include:

  1. Every hash is different from another.
  2. Same Hash value will be always produced for the same message.
  3. Impossible to decide input based on the hash value.
  4. Even a small change to the input whole hash will be changed. Hashing helps us to see if the data has tampered or not. For example, you have downloaded a piece of important information, to see if the data is changed or not, you can run the data through the hashing algorithm and compare the hash of the data and hash of the received data. If both the hashes are same the data is not changed and if the hash doesn’t match, the data is altered before you received it.