Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Created January 23, 2017 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayesh15111988/88c3724bbc3da1090c13d03f286b16ea to your computer and use it in GitHub Desktop.
Save jayesh15111988/88c3724bbc3da1090c13d03f286b16ea to your computer and use it in GitHub Desktop.
A Sample code to demonstrate Swift error handling
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