Extensions in Swift

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

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 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 UserModel {
//your functionality
}

You can use this for conforming protocols

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

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

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

Thank you !

I am Swift developer and makes iOS apps

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store