Code reusability using swift extension

This post is about how to write clean, optimised code using code reusability. Code reusability is very big topic so I write about the code we use most in our daily programming life.

Alert

Avoid

Most of programmer usually write alert as following.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //----present alert
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(OKAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

we should avoid to write complete alert code in each and every place. Instead more clean way is to reuse code using extension.

Follow

Its very clear, clean way to use alert in whole app. Make viewcontroller extension as following and call alert function wherever needed.

Now we can call alert using only one line of code

extension UIViewController {

  func alert(message: String, title: String = "") {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
  }

}
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //----present alert
        alert(message: "Message", title: "Title") //--just one line everywhere
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s