0
0
Swiftprogramming~15 mins

Why extensions add capability without modifying in Swift - See It in Action

Choose your learning style9 modes available
Why extensions add capability without modifying
📖 Scenario: Imagine you have a simple app that works with numbers. You want to add new features to numbers without changing the original number code. This is like adding new tools to your toolbox without breaking the old ones.
🎯 Goal: You will learn how to use extension in Swift to add new functions to existing types without changing their original code.
📋 What You'll Learn
Create a variable with a number
Create an extension for the Int type
Add a new function inside the extension
Call the new function and print the result
💡 Why This Matters
🌍 Real World
Extensions let developers add new features to existing code safely, like adding new tools to a toolbox without breaking old tools.
💼 Career
Understanding extensions is important for Swift developers to write clean, maintainable, and flexible code in apps.
Progress0 / 4 steps
1
Create a variable with a number
Create a variable called myNumber and set it to 10.
Swift
Need a hint?

Use var myNumber = 10 to create the variable.

2
Create an extension for the Int type
Create an extension for the Int type. Inside it, define a function called squared() that returns the number multiplied by itself.
Swift
Need a hint?

Use extension Int { func squared() -> Int { return self * self } }.

3
Call the new function on the variable
Call the squared() function on myNumber and store the result in a variable called result.
Swift
Need a hint?

Use let result = myNumber.squared() to call the function.

4
Print the result
Print the value of result using print().
Swift
Need a hint?

Use print(result) to show the output.