官术网_书友最值得收藏!

How to do it...

  1. As usual, let's create a new playground named ErrorHandling.
  2. Let's create now a new error type for a function that will sign up a new user in a system:
      enum SignUpUserError: ErrorType{ 
 
        case InvalidFirstOrLastName 
        case InvalidEmail 
        case WeakPassword 
        case PasswordsDontMatch 
      } 
  1. Now, create the sign up function that throws errors we made in the previous step, if any:
      func signUpNewUserWithFirstName(firstName: String, lastName: String, email: String, password: String, confirmPassword: String) throws{ 
 
        guard firstName.characters.count> 0 &&lastName.characters.count> 0 else{ 
 
          throw SignUpUserError.InvalidFirstOrLastName 
        } 
 
        guard isValidEmail(email) else{ 
          throw SignUpUserError.InvalidEmail 
        } 
 
        guard password.characters.count> 8 else{ 
          throw SignUpUserError.WeakPassword 
        } 
 
        guard password == confirmPassword else{ 
          throw SignUpUserError.PasswordsDontMatch 
        } 
 
        // Saving logic goes here 
 
        print("Successfully signup user") 
 
        } 
 
        func isValidEmail(email:String) ->Bool { 
 
          let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" 
          let predicate = NSPredicate(format:"SELF MATCHES %@", emailRegex) 
          return predicate.evaluateWithObject(email) 
        } 
  1. Now, let's see how to use the function and catch errors:
       do{ 
         trysignUpNewUserWithFirstName("John", lastName: "Smith", email: "john@gmail.com", password: "123456789", confirmPassword: "123456789") 
       } 
       catch{ 
         switch error{ 
           case SignUpUserError.InvalidFirstOrLastName: 
             print("Invalid First name or last name") 
           case SignUpUserError.InvalidEmail: 
             print("Email is not correct") 
           case SignUpUserError.WeakPassword: 
             print("Password should be more than 8 characters long") 
           case SignUpUserError.PasswordsDontMatch: 
             print("Passwords don't match") 
           default: 
             print(error) 
         } 
       } 
主站蜘蛛池模板: 保康县| 隆回县| 平湖市| 赣榆县| 洪江市| 景泰县| 石泉县| 镇坪县| 龙南县| 卢湾区| 沅江市| 金门县| 嫩江县| 凉城县| 阿合奇县| 西吉县| 秦安县| 通江县| 辉县市| 永和县| 绥化市| 察隅县| 桂林市| 华亭县| 肇源县| 榆中县| 杨浦区| 江达县| 鸡西市| 柳江县| 措勤县| 阜康市| 桑日县| 广安市| 伊吾县| 榆林市| 武乡县| 峡江县| 宜川县| 三原县| 屯昌县|