0
0
Swiftprogramming~15 mins

CompactMap for optional unwrapping in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
CompactMap for optional unwrapping
📖 Scenario: You have a list of strings representing ages of people. Some strings are valid numbers, and some are not. You want to get a list of only the valid ages as integers.
🎯 Goal: Build a Swift program that uses compactMap to convert an array of optional strings into an array of non-optional integers, filtering out invalid entries.
📋 What You'll Learn
Create an array of strings called ageStrings with the exact values: ["25", "thirty", "42", "", "18"]
Create a variable called validAges that uses compactMap on ageStrings to convert strings to Int
Print the validAges array
💡 Why This Matters
🌍 Real World
Filtering and converting user input or data from text sources where some values may be invalid or missing.
💼 Career
Data cleaning and transformation is a common task in app development, especially when handling user input or external data.
Progress0 / 4 steps
1
Create the array of age strings
Create an array called ageStrings with these exact string values: ["25", "thirty", "42", "", "18"]
Swift
Need a hint?

Use square brackets to create an array of strings.

2
Use compactMap to convert strings to integers
Create a variable called validAges that uses compactMap on ageStrings to convert each string to an Int.
Swift
Need a hint?

Use compactMap with a closure that tries to convert each string to Int.

3
Print the valid ages
Write a print statement to display the validAges array.
Swift
Need a hint?

Use print(validAges) to show the result.

4
Run and check the output
Run the program and observe the output. It should print the array of valid ages as integers.
Swift
Need a hint?

The output should be [25, 42, 18] because only these strings convert to integers.