'Is it proper to add an extension to UIViewController class, or is there a preferred way of adding another method to an established Swift Class?
I have an iOS app with multiple subclasses of UIViewControllers. There are many type of UIAlertControllers I might need to use based on user interaction, internet connection, and catching any other fatal errors.
So I wrote the extension for UIViewController below, which works just fine. And I can call from any of my UIViewControllers as simply as:
myErrors(error: MyErrors.e1.rawValue, title: "Internet Error", msg: "Unable to connect to Internet\nTry Again?")
While this works, I do not know if it's proper to add an extension to UIViewController. Is this considered bad practice? Is there another way I should be pursuing this?
extension UIViewController {
func myErrors(error: MyErrors, title: String, msg: String)
{
var title = ""
var message = ""
switch error {
case .e1:
title = String(format: "%@", title)
message = String(format: "Database Error %03d%@\n", error.rawValue, msg)
case .e2:
title = String(format: "%@", title)
message = String(format: "Internet Error %03d%@\n", error.rawValue, msg)
case .e3:
title = String(format: "%@", title)
message = String(format: "User Error %03d%@\n", error.rawValue, msg)
}
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
switch error {
case .e1:
alert.addAction(UIAlertAction(title: "No", style: .init(rawValue: 0)!, handler: { (action: UIAlertAction!) in
// ..log error
//...proceed to code based on No ....
}))
alert.addAction(UIAlertAction(title: "Yes", style: .init(rawValue: 0)!, handler: { (action: UIAlertAction!) in
// ..log error
//...code based on Yes ....
}))
case .e2:
// No user option availabe in this alert, just OK
// ... do all logging of errors
// proceed
case .e3:
// Add specific acctions to this error
// ... do all logging of errors
// proceed
}
self.present(alert, animated: true, completion: nil)
}
}
Solution 1:[1]
You can create protocol+extension, otherwise you will have access to myError method even you don't need it for particular UIViewController.
protocol ErrorPresenting {
func presentAlert(for error: MyErrors, title: String, msg: String)
}
extension ErrorPresenting where Self: UIViewController {
func presentAlert(for error: MyErrors, title: String, msg: String) {
// Since you state that this extensions for UIViewController, you can reach view.
// Put your method here.
view.present(alert, animated: true)
}
}
Usage is simple:
class MyController: UIViewController, ErrorPresenting {
// You can reach presentAlert method from this controller now.
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eyup Kazim Goymen |
