0
0
Swiftprogramming~30 mins

Extensions with constraints in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Extensions with constraints
📖 Scenario: You are building a simple app that works with collections of numbers. You want to add a new feature to calculate the sum of all elements, but only for collections that hold numbers.
🎯 Goal: Create an extension with constraints to add a sumElements() method to collections of numbers.
📋 What You'll Learn
Create an array of integers called numbers with the values [3, 7, 2, 9].
Create a constant called isNonEmpty that checks if numbers is not empty.
Write an extension for Collection where the element type is Int to add a method sumElements() that returns the sum of all elements.
Print the result of calling sumElements() on numbers.
💡 Why This Matters
🌍 Real World
Extensions with constraints let you add useful features to existing types only when they meet certain conditions, like holding numbers. This helps keep your code safe and organized.
💼 Career
Understanding how to write constrained extensions is important for Swift developers to create reusable and type-safe code, a common task in app development.
Progress0 / 4 steps
1
Create the initial array
Create an array called numbers with the exact values [3, 7, 2, 9].
Swift
Need a hint?

Use let numbers = [3, 7, 2, 9] to create the array.

2
Add a configuration constant
Create a constant called isNonEmpty that is true if numbers is not empty, otherwise false.
Swift
Need a hint?

Use !numbers.isEmpty to check if the array is not empty.

3
Write the extension with constraints
Write an extension for Collection where the element type is Int. Add a method called sumElements() that returns the sum of all elements using reduce(0, +).
Swift
Need a hint?

Use extension Collection where Element == Int and reduce(0, +) inside sumElements().

4
Print the sum of elements
Print the result of calling sumElements() on the numbers array.
Swift
Need a hint?

Use print(numbers.sumElements()) to display the sum.