0
0
Swiftprogramming~15 mins

Tuples for grouped values in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Tuples for grouped values
📖 Scenario: You are organizing a small fruit shop's inventory. Each fruit has a name and a price per kilogram. You want to group these two pieces of information together for easy handling.
🎯 Goal: Build a Swift program that uses tuples to group fruit names with their prices, then access and display this grouped information.
📋 What You'll Learn
Create a tuple with a fruit name and its price
Create a second tuple with another fruit name and price
Access tuple elements by name
Print the fruit name and price in a friendly message
💡 Why This Matters
🌍 Real World
Grouping related data like fruit name and price helps organize inventory information clearly and accessibly.
💼 Career
Understanding tuples is useful for developers to group small sets of related data without creating full custom types.
Progress0 / 4 steps
1
Create the first fruit tuple
Create a tuple called fruit1 with two named elements: name set to "Apple" and price set to 2.5.
Swift
Need a hint?

Use let fruit1 = (name: "Apple", price: 2.5) to create the tuple with named elements.

2
Create the second fruit tuple
Create a tuple called fruit2 with two named elements: name set to "Banana" and price set to 1.2.
Swift
Need a hint?

Use the same tuple syntax as before but with the new values.

3
Access tuple elements
Create two constants called firstFruitName and secondFruitPrice. Set firstFruitName to the name element of fruit1. Set secondFruitPrice to the price element of fruit2.
Swift
Need a hint?

Use dot notation like fruit1.name to get the element from the tuple.

4
Print the fruit information
Print a message using print that says: "The first fruit is Apple and the second fruit costs 1.2 dollars per kg." Use the constants firstFruitName and secondFruitPrice inside the message with string interpolation.
Swift
Need a hint?

Use print("The first fruit is \(firstFruitName) and the second fruit costs \(secondFruitPrice) dollars per kg.").