A Sample code to demonstrate Swift error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
enum PasswordError: Error { | |
case TooShort | |
case NoNumber | |
case CustomMessage(message: String) | |
} | |
class PasswordChecker { | |
func checkPassword(password: String) throws -> Bool { | |
guard password.characters.count >= 8 else { | |
throw PasswordError.TooShort | |
} | |
let numberRegEx = ".*[0-9]+.*" | |
let texttest1 = NSPredicate(format:"SELF MATCHES %@", numberRegEx) | |
guard texttest1.evaluate(with: password) == true else { | |
throw PasswordError.NoNumber | |
} | |
guard password.lowercased() != "password" else { | |
throw PasswordError.CustomMessage(message: "Common keyword used as a password") | |
} | |
return true | |
} | |
func checkMyPassword(password: String) { | |
let validatedPasswordStatusWithOptional = try? self.checkPassword(password: password) | |
let validatedPasswordStatusWithForce = try! self.checkPassword(password: password) | |
do { | |
let passwordCheckFlag = try self.checkPassword(password: password) | |
print(passwordCheckFlag) | |
// Do some amazing things with returned password check flag | |
} catch PasswordError.TooShort { | |
print("Password is too short") | |
} catch PasswordError.NoNumber { | |
print("Password must contain at least one number") | |
} catch PasswordError.CustomMessage(message: let message) { | |
print(message) | |
} catch { | |
print("Unknown Error Occurred while trying to validate password") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment