Thursday, 20 April 2017

Protocol extension

Example: Login screen

Let’s do a more practical example. Let’s say you have a login screen that needs to validate the username and password to make sure they are well-formed — not too short, not too long, no invalid characters — before you actually send a web service request. This is a fairly common thing to do in iOS apps.
protocol ValidatesUsername { func isUsernameValid(password: String) -> Bool }
extension ValidatesUsername {
func isUsernameValid(username: String) -> Bool {
if /* username too short */
{ return false }
else if /* username has invalid characters */ { return false }
else { return true }
}
}
The validation logic doesn’t sit in a class but in a protocol extension. The protocol declares the isUsernameValid() method and the extension implements it.
To add this logic into the view controller, all you have to do is this:
class LoginViewController: UIViewController, ValidatesUsername, ValidatesPassword {
By making the view controller conform to the protocols for the ValidatesUsernameand ValidatesPassword mixins, it automatically pulls the isUsernameValid() and isPasswordValid() methods into the code.
And you can simply call those methods as if they were the view controller’s own:
class LoginViewController: UIViewController, ValidatesUsername, ValidatesPassword {
  @IBAction func loginButtonPressed() {
    if isUsernameValid(usernameTextField.text!) && 
       isPasswordValid(passwordTextField.text!) {
      // proceed with login
    } else {
      // show alert
    }
  }
}
This is a nice trick to keep your view controllers clean without having to use extra helper objects. I think this is pretty cool. And you can also easily reuse these mixins in other view controllers and in other projects.

Know more about protocol-oriented programming 


No comments:

Post a Comment