- iOS Programming Cookbook
- Hossam Ghareeb
- 189字
- 2021-07-09 18:29:45
How to do it...
- As usual, let's create a new playground named ErrorHandling.
- 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 }
- 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) }
- 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) } }
推薦閱讀
- Linux設備驅動開發詳解:基于最新的Linux4.0內核
- Mastering ElasticSearch
- Windows Server 2019 Cookbook
- Linux系統架構與運維實戰
- 白話區塊鏈
- Windows Server 2012網絡操作系統企業應用案例詳解
- 8051軟核處理器設計實戰
- 直播系統開發:基于Nginx與Nginx-rtmp-module
- Linux命令行大全(第2版)
- Linux設備驅動開發
- Social Data Visualization with HTML5 and JavaScript
- Red Hat Enterprise Linux 6.4網絡操作系統詳解
- Learn SwiftUI
- Office 365 User Guide
- Linux內核修煉之道