Updated April 17, 2023
Introduction to Swift extension
The swift extension is an added advantage to the Swift programming language as it enhances the entire feature by adding more functionality and capability to the already existing data structures in swift language, namely structure, enumeration, class, or any other type of protocol structure or type. Swift extension also aids for other features in the language like those types which don’t consist of source code within the repository for execution. Swift Extension types include extensions for int, bool types, etc. All these extensions with features help in making instantiation and properties computation quite easy.
Syntax
The syntax flow for the swift extension is as follows :
extension Struct_Enum_Extnsion_Type
{
// add functionality and enhancement to the above type of extension
}
Where,
extension – It signifies that swift extension is used for performing the swift programming followed by any class name.
{
Adding functionality helps in making the extension type more enhancing.
}
How does Swift extension work?
- Swift extension has a working pattern which improvises and enhances the entire feature by providing some of the enhanced functionalities to the data structure and its values.
- Sometimes the source code does not exist within the repository for access then at that time, the swift extension comes as a savior, which behaves almost like categories of objective C.
- There is some added advantage of using an extension as it helps in making the entire programming language reusable, flexible, and robust.
- It has the property to add some computed instance properties that help in getting instance values and another type of property as well.
- It provides many other types of new initializers for support as well.
- Initializers present as part of extension helps in many ways as it helps in extending another type of data and customized type of initializer or parameter.
- It also helps in making another type of initializers, instance method, and type methods inclined and used with repetition of Int types in the methods indicating to get a return type.
- Some extensions which help in mutating have the capacity to modify the self and its type of properties which embarks the change and modification by a mutation on the original implementation.
- The addition of subscripts is also possible using the extension as it helps in making the old type of properties added with the new subscript.
- Swift extensions also can inherit the properties for the old type into a new type using a type of extension at the time of implementation.
- Extensions also get created using conforming protocols with the extension in the methods being implemented within the codebase.
- Extensions also help in code separation as they can differentiate the code and give it an edge by segregating and providing enhanced code in the Swift programming language.
Examples
Different examples are mentioned below:
Example #1
This program demonstrates the Swift extension, which inherits the computed instance and type properties with all types of extensions, specifically int type with various manipulation as shown in the output.
import Foundation
import Glibc
extension Int
{
var no_add: Int {return self + 150 }
var no_sub: Int { return self - 50 }
var no_mul: Int { return self * 20 }
var no_div: Int { return self / 30 }
}
let no_of_addition = 12.no_add
print("Addition_includes \(no_of_addition)")
let no_of_division = 68.no_div
print("Division_includes \(no_of_division)")
let no_of_multiplication = 82.no_mul
print("Multiplication_includes \(no_of_multiplication)")
let no_of_subtraction = 125.no_sub
print("Subtraction_includes \(no_of_subtraction)")
let miscellaneous = 12.no_add + 26.no_sub
print("Miscellaneous_makes \(miscellaneous)")
Output:
Example #2
This program demonstrates the instance class or the method class, which inherits the properties of a swift extension within the subclasses as well as all the properties as shown in the output.
import Foundation
import Glibc
extension Int {
func computer_subjects(analyse_and_summarize: () -> ()) {
for _ in 1..<self {
analyse_and_summarize()
}
}
}
2.computer_subjects(analyse_and_summarize: {
print("Control_under_first_sub_block..")
})
6.computer_subjects(analyse_and_summarize: {
print("Control_under_first_sub_block..")
})
Output:
Example #3
This program demonstrates the usage of swift extension for the nested type of data structure, enum, or enhanced classes, as shown in the output.
import Foundation
import Glibc
extension Int {
enum vehicles {
case car
case truck
case bus
case scooter
case blend
}
var print: vehicles {
switch self {
case 0:
return .car
case 1:
return .truck
case 2:
return .bus
case 3:
return .scooter
default:
return .blend
}
}
}
func result(numb: [Int]) {
for k_0 in numb {
switch k_0.print {
case .car:
print(" Porsche_xl ")
case .truck:
print(" Mahindra_vi ")
case .bus:
print(" Volvo+0 ")
case .scooter:
print(" pep++ ")
default:
print(" autorick_shaw ")
}
}
}
result(numb: [0, 1, 3, 4, 6, 5])
Output:
Example #4
This program demonstrates the mutation of the instances, which means that the value can transform themselves according to the requirement within the method as shown in the output for computing the cube area.
import Foundation
import Glibc
extension Double {
mutating func cube() {
let val_p = 3.256
self = val_p * self * self * self
}
}
var cube_try_0 = 2.11
cube_try_0.cube()
print("Cube_area of a cube is: \(cube_try_0)")
var cube_try_1 = 3.66
cube_try_1.cube()
print("Cube_area of a cube is: \(cube_try_1)")
var cube_try_2 = 256.12
cube_try_2.cube()
print("Cube_area of a cube is: \(cube_try_2)")
Output:
Example #5
This program demonstrates the protocol extension with some added constraints on the set of declared array and collection conforming to the type and properties of the entire set using the extension as shown in the output.
import Foundation
import Glibc
extension Collection where Element: Equatable {
func equal_all_condn() -> Bool {
for Element in self {
if Element != self.first {
return false
}
}
return true
}
}
let eql_cllcn_no = [213, 108, 206, 105, 150]
let spillted_no = [300, 300, 300, 300, 300]
print(eql_cllcn_no.equal_all_condn())
print(spillted_no.equal_all_condn())
Output:
Conclusion
It plays a very significant and powerful role in a swift programming language as it helps programmers and provides them with the ability to manipulate the elements according to the accessibility. It helps in enhancing the code and making the code in an understandable and readable format. It helps in managing the codebase with the usage of the swift extension.
Recommended Articles
We hope that this EDUCBA information on “Swift extension” was beneficial to you. You can view EDUCBA’s recommended articles for more information.