0
0
Swiftprogramming~15 mins

Extending built-in types in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Extending built-in types
📖 Scenario: Imagine you want to add a new feature to Swift's built-in Int type. You want to check if a number is even or odd easily, just like calling a simple property.
🎯 Goal: You will create an extension to the Int type that adds a computed property called isEven. This property will return true if the number is even, and false if it is odd.
📋 What You'll Learn
Create an extension for the built-in Int type
Add a computed property called isEven that returns a Bool
Use the modulo operator (%) to determine if a number is even
Test the new property with a few example numbers
Print the results to the console
💡 Why This Matters
🌍 Real World
Extending built-in types lets you add useful features to existing data types without changing their original code. This helps keep your code clean and reusable.
💼 Career
Many Swift developers extend built-in types to add custom behavior, making their apps more expressive and easier to maintain.
Progress0 / 4 steps
1
Create an integer variable
Create a variable called number and set it to the integer 10.
Swift
Need a hint?

Use var number = 10 to create the variable.

2
Create an extension for Int
Create an extension for the built-in Int type. Inside it, add a computed property called isEven that returns a Bool. For now, just return false inside the property.
Swift
Need a hint?

Use extension Int { var isEven: Bool { return false } } to create the extension and property.

3
Implement the isEven logic
Change the isEven computed property to return true if the number is even, and false if it is odd. Use the modulo operator % to check if self % 2 == 0.
Swift
Need a hint?

Use return self % 2 == 0 inside the computed property.

4
Test and print the result
Use print to display the result of number.isEven. This will show true if number is even, or false if odd.
Swift
Need a hint?

Use print(number.isEven) to show the result.