Extensions in Swift are a powerful feature that allows you to add new functionality to existing classes, structs and more.
Extensions enable you to extend types, create custom accessors, and enhance the types you work with. Here we will explore some useful extensions in Swift.
When we use extensions in Swift it saves a lot of code by just a few lines of code. Extensions are those you can write your function in default classes of iOS.
Useful Extensions
- Apply Border in your view:- If you want to use the border in your view, it must be the same in the whole application. You must create an extension of the border so that if you want to change the size or colour of the border it will automatically reflect in your whole application.
12345678910111213141516171819extension UIView {func applyBorder() -> Void {self.layer.borderColor = UIColor.black.cgColor // change yor colorself.layer.borderWidth = 1.5self.layer.shadowColor = UIColor.black.cgColorself.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)}}// or pass color while using this functionextension UIView {func applyBorder(colours: UIColor) -> Void {self.layer.borderColor = colours.cgColorself.layer.borderWidth = 1.5self.layer.shadowColor = UIColor.black.cgColorself.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)}}
How to use:-
12345yourView.applyBorder()// oryourView.applyBorder(colours: UIColor.green) - Remove String:- Lots of times you want to remove the substring from a string, It is more irritating to use again and again replacingOccurrences function. So its better to create the extension of removing the substring from a string.
1234567extension String {func removeString(completeString:String , remove: String) -> String {let aString = completeStringlet newString = aString.replacingOccurrences(of: "", with: remove, options: .literal, range: nil)return newString}}
How to use:-
12345let name = string.removeString(completeString:"abcdef" , remove: "def")output isname = "abc" - Set image and download image:- In almost every application you have to download the images from the URL. We strongly recommend using the Kingfisher library for downloading images from the server and caching images. So it’s better to create the extension of UIImageView and then create the function in the UIImageView class where you can download and cache the images and also set the placeholder while downloading the image.
12345678910111213141516import Kingfisherextension UIImageView {func setImage(imageUrl : String? ) {if URL(string: imageUrl) != nil && imageUrl.count > 0 {let resource = ImageResource(downloadURL: URL(string: imageUrl)!, cacheKey: imageUrl)self.contentMode = .scaleAspectFitself.kf.setImage(with: resource, placeholder: UIImage(named : "placeholder") , options: nil, progressBlock: nil, completionHandler: nil)}else{self.image = UIImage(named : "placeholder")}}}
How to use it:-
123yourImage.setImage(imageUrl: ImageUrl)//set your image to UIImageView - Width and height of string:- If you want to find the width and height of the string, use the below extension.
1234567891011121314extension String {func widthOfString(usingFont font: UIFont) -> CGFloat {let fontAttributes = [NSFontAttributeName: font]let size = self.size(attributes: fontAttributes)return size.width}func heightOfString(usingFont font: UIFont) -> CGFloat {let fontAttributes = [NSFontAttributeName: font]let size = self.size(attributes: fontAttributes)return size.height}}
How to use it:-
1let stringSize = buttonText.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) - Load XIB:- Xib plays an important role in the iOS application you use many times or almost on each page of the application. So create the extension of Bundle where you can load your Xib.
12345678910extension Bundle {static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {return view}fatalError("Could not load view with type " + String(describing: type))}}
How to use it:-
123var emptyView : EmptyView? // your xibemptyView = Bundle.loadView(fromNib: "EmptyView", withType: EmptyView.self)// it will load your xib
Conclusion
Extensions are a key tool for app developers in Swift to enhance and customize their codebase efficiently. They provide a flexible way to add new methods, computed properties and initializers.
That’s all for this article. We hope you liked this article.
You can keep learning more with the Mobikul Blogs.
You may also check our Flutter app development page.