Extensions in Swift

What is the Extensions? | How to create extension in Swift 4?

Anand Nimje
Apr 15, 2018 · 4 min read

I have used Extension for Label in my previous blog. There i have added all my code inside the extension but why i have do this you suppose to know in this chapter i will be clear all this things how good any very easy to create and use in your own project.

What is the Extensions?

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).

Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

Source - Apple documents.

Create your first extension

Extension are pretty easy to create by writing out side the your class or Controller class like extension and your class name

extension UserModel {
//your functionality
}

You can use this for conforming protocols

If you are using table view inside your project then you need to confirm your protocols with the methods but if you having lots of methods inside your projects and other protocols also there then its hard to manage things and mostly we are facing problems for finding the code inside our class.

Class without Extension

Here in this class you able to see this is the very normal code at the beginning level every developer they starting development like this.

Check all objects and function of class you can see here project navigator
with out extension all object and methods

This is very small class if you start working on real projects then there will be more functions and objects will be more then hard to find or check your code quickly.

With extension and MARK function identity

Now you are able to see very clearly your code is divided into groups with proper function identity with Extension very clearly code define here.

Extra tip - “MARK” this is coming in the documentation process. You can visit this (NSHipster) link for better understanding of code documentation in Swift Language.There they have clear lots of things.

Code Separation with Extension

You can write with the help of extension separate protocols methods with belongs to particular protocol. Its very easy to understandable code when you what to work or do modification in future in the same class again.

class Mango: UIViewController{

override func viewDidLoad() {
super.viewDidLoad()
}
}
//MARK: - TableView Data Source Methods
extension Mango: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

}
}

Let’s see the uses of Extensions

Here I am creating model it will support multiple custom initializer.

struct UserModel: Codable{
var name: String
var userId: Int
}
extension UserModel {
enum CodingKeys: String, CodingKey {
case name = "user_name"
case userId = "user_id"
}
}
extension UserModel{
//MARK: - Initialization
init(_ dic: [String: Any]) {
self.name = dic["user_name"] as? String ?? ""
self.userId = dic["user_id"] as? Int ?? 0
}
}

One model you can use different way 🚀

Custom Initializer use
let dictionary = ["user_name":"Rahul", "user_id":43] as [String : Any]//Model Initialization types
//1
let model = UserModel(name: "Anand", userId: 1)
model.name
//2let newModel = UserModel(dictionary)
newModel.name
//3 do {
// data we are getting from network request
let decoder = JSONDecoder()
let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) //test data
let response = try decoder.decode(UserModel.self, from: data)
print(response) //Output
} catch { print(error) }

Let’s try for other things

Extension you can create for any class like -

extension String {
//MARK : - For First Capital letter of String
private func capitalizingFirstLetter() -> String {
let first = String(self.prefix(1)).capitalized
let other = String(self.dropFirst())
return first + other
}

mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}//Use of Extension
var testString = "orange"
testString.capitalizeFirstLetter()
print(testString) //Output - Orange

Conclusion

In this part, i have covered for creating the Extension and uses of it. Now you got understanding from basic use to advance. You can make your own Extension for any class, structure, enumeration, or protocol. The Extension is a really powerful feature in Swift Language. You can use your code to making more simple and understandable functionality. You can write separated and easy to manageable code as per your understanding, requirements. I have added Git repo for Extensions you can check it. 😊 🎉


Thank you !

If you having any query regarding this tutorial ? Twitter me: @Anand

Anand Nimje

Written by

I am Swift developer and makes iOS apps

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade