Extensions add new functionality to an existing type. Type can be class, structure, enumeration or protocol. This includes the ability to extend types for which you do not have access to the original source code.
Extensions in Swift can add computed instance properties and computed type properties. Extension helps to use more usable method by declaring it once in extension which means no need to redeclare and repeat same method in every class.
Extension Syntax
Declare extensions with the extension
keyword:
extension SomeType {
// new functionality to add to SomeType goes here
}
This example adds method to Swift's build-in UIViewController
type, to provide basic support for working with UIAlertController
extension UIViewController {
func alert(title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(alertAction)
self.present(alertController, animated: true, completion: nil)
}
}
Now, Whenever you want to use UIAlertController
. You just need to add this single line and you can access this extension for every UIViewController
class
self.alert(message: "Enter Message", title: "Enter Title")
References :-
https://docs.swift.org/swift-book/LanguageGuide/Extensions.html