0
0
Swiftprogramming~10 mins

Ternary conditional operator in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Ternary Conditional Operator in Swift
📖 Scenario: Imagine you are building a simple app that checks if a person is old enough to vote. You want to decide if the person can vote or not based on their age.
🎯 Goal: You will create a program that uses the ternary conditional operator to decide if a person is eligible to vote. The program will print "Can vote" if the person is 18 or older, and "Cannot vote" if younger.
📋 What You'll Learn
Create a variable called age with the value 20
Create a variable called votingStatus that uses the ternary conditional operator to check if age is 18 or more
Use the ternary conditional operator with the condition age >= 18
Set votingStatus to "Can vote" if true, otherwise "Cannot vote"
Print the value of votingStatus
💡 Why This Matters
🌍 Real World
Ternary operators help make quick decisions in code, like checking user age for permissions or showing different messages.
💼 Career
Understanding ternary operators is useful for writing clean and concise code in app development and many programming tasks.
Progress0 / 4 steps
1
Create the age variable
Create a variable called age and set it to the integer value 20.
Swift
Need a hint?

Use var age = 20 to create the variable.

2
Create the votingStatus variable using the ternary operator
Create a variable called votingStatus that uses the ternary conditional operator with the condition age >= 18. Set it to "Can vote" if true, otherwise "Cannot vote".
Swift
Need a hint?

Use the syntax condition ? valueIfTrue : valueIfFalse.

3
Use the ternary operator in a simple expression
Make sure the variable votingStatus uses the ternary conditional operator with the exact condition age >= 18 and the exact values "Can vote" and "Cannot vote".
Swift
Need a hint?

Check that the ternary operator uses the condition age >= 18 exactly.

4
Print the votingStatus
Write a print statement to display the value of the variable votingStatus.
Swift
Need a hint?

Use print(votingStatus) to show the result.