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
    }
}

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –  paypal.me/SandeshSardar

download

Advertisements