Usage of Swift Extensions and Protocol Extensions
Usage of Swift Extensions and Protocol Extensions
In the Swift programming language, extensions and protocol extensions allow you to make your code more modular and readable by adding new features and functionalities to existing types. Swift Extensions are used to add extra functions, computed properties, or initializers to a class, structure, or enum. Protocol Extensions, on the other hand, enable you to add default behavior to all types that conform to a protocol and are a powerful feature of Swift.
What are Swift Extensions and How Are They Used?
Swift Extensions are a practical way to add new functions to an existing type. In this way, you can extend the functionality of a class, struct, or enum even if you do not have access to its original source code. They are especially often used on primitive types. For example, it is possible to add a new property to the Int type:
extension Int {
var karesi: Int {
return self * self
}
}
let sayi = 7
print(sayi.karesi) // Prints 49
In the example above, we added a new property called karesi to the Int type. This allows us to easily get the square of any Int value. It is also possible to add functions with Swift Extensions.
Protocol Extensions: Define Default Behaviors
Protocol Extensions allow you to define default properties and methods for all types that conform to a specific protocol. This helps prevent code repetition and establishes a cleaner structure by avoiding multiple inheritance. In the example below, let's look at a protocol and its extended version:
protocol Selamlanabilir {
func selamla()
}
extension Selamlanabilir {
func selamla() {
print("Hello, Swift world!")
}
}
struct Kisi: Selamlanabilir {}
let ali = Kisi()
ali.selamla() // Prints "Hello, Swift world!"
In this example, we added a default selamla function to the Selamlanabilir protocol. The Kisi structure automatically gains this function as soon as it adopts the protocol.
Advantages of Using Swift Extensions and Protocol Extensions
By using Swift Extensions and Protocol Extensions, you can reduce code repetition and establish a clean, readable structure. You can also quickly add new behaviors to existing library types. With Protocol Extensions, you can define default behavior and provide a consistent interface in different parts of your software. In short, with these two Swift features, you can both save time and develop sustainable projects.

Yorum Gönder