Skip to main content

Swift Extension

Extension are used to provide new features to existing classes, structure ,enumeration and protocol data types. We can define extension in using of following syntax.

extension extensionType{
//Provide definitions

Example of Extension

//Add extension to Int class

extension Int {
    //Adding on factorial calculation functionality to integer
    func factorial()->Int{
       if(self<=1) { return 1 }
       else { return self * (self-1).factorial() }

var result = 4.factorial()
var data = 5

print("Factorial of 4: \(result)") 

result = data.factorial()

print("Factorial of \(data): \(result)") 


Factorial of 4: 24
Factorial of 5: 120


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment