0
0
Swiftprogramming~30 mins

Type inference by the compiler in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Type inference by the compiler
📖 Scenario: Imagine you are creating a simple Swift program to store information about a fruit basket. You want to use the compiler's ability to guess the type of your variables automatically, so you don't have to write the type explicitly.
🎯 Goal: Build a Swift program that uses type inference to create variables for fruit names and quantities, then prints them.
📋 What You'll Learn
Create variables using type inference with exact names and values
Add a constant to hold the total number of fruits
Use a for loop to print each fruit and its quantity
Print the total number of fruits at the end
💡 Why This Matters
🌍 Real World
Type inference helps programmers write cleaner and shorter code by letting the compiler figure out data types automatically.
💼 Career
Understanding type inference is important for Swift developers to write efficient and readable code, especially in app development.
Progress0 / 4 steps
1
Create variables with type inference
Create three variables called appleCount, bananaCount, and orangeCount with values 5, 3, and 7 respectively. Do not specify their types explicitly.
Swift
Need a hint?

Just write var appleCount = 5 and similarly for the others. Swift will guess the type as Int.

2
Add a constant for total fruits
Create a constant called totalFruits that adds appleCount, bananaCount, and orangeCount. Use type inference and do not specify the type explicitly.
Swift
Need a hint?

Use let totalFruits = appleCount + bananaCount + orangeCount to create the constant.

3
Use a for loop to print each fruit and quantity
Create a dictionary called fruitBasket with keys "Apple", "Banana", and "Orange" and their respective counts from appleCount, bananaCount, and orangeCount. Then use a for loop with variables fruit and count to iterate over fruitBasket and print each fruit and its count using print("\(fruit): \(count)").
Swift
Need a hint?

Use a dictionary literal and a for loop with tuple unpacking to print each fruit and count.

4
Print the total number of fruits
Write a print statement to display the text Total fruits: followed by the value of totalFruits using string interpolation.
Swift
Need a hint?

Use print("Total fruits: \(totalFruits)") to show the total count.