我的密码强度标准如下:
长度为8个字符否特殊字符Atleast 1个数字Atleast 1个字母
更新: Xcode 8.3.2•Swift 3.1
enum PasswordError: String, Error { case eightCharacters case oneUppercase case oneLowercase case oneDecimalDigit } extension String { func validatePassword() throws { guard count > 7 else { throw PasswordError.eightCharacters } guard rangeOfCharacter(from: .uppercaseLetters) != nil else { throw PasswordError.oneUppercase } guard rangeOfCharacter(from: .lowercaseLetters) != nil else { throw PasswordError.oneLowercase } guard rangeOfCharacter(from: .decimalDigits) != nil else { throw PasswordError.oneDecimalDigit } } }
let myPass = "12345678" do { try myPass.validatePassword() print("valid password action") } catch let error as PasswordError { print("Password error:", error) switch error { case .eightCharacters: print("Needs At Least Eight Characters action") case .oneUppercase: print("Needs At Least one Uppercase action") case .oneLowercase: print("Needs At Least one Lowercase action") case .oneDecimalDigit: print("Needs At Least One DecimalDigit action") } } catch { print("error:", error) }