0

I'm doing something wrong here, but I'm not sure quite what I'm doing wrong.

For some reason my switch case always goes to the default case instead of the proper case.

I added the default because before it was saying that the switch needed it.

Here is my function call with the password passed into it

do { try self.validate(password: password) } catch { print("Error Label", error.localizedDescription) // errorLabel.text = error.localizedDescription } 

This is the function itself:

 func validate(password: String) throws { guard password.count == 0 else { print("too short") HapticsManager.shared.vibrate(for: .error) throw ValidationError.noPass } guard password.count > 3 else { print("too short") HapticsManager.shared.vibrate(for: .error) throw ValidationError.tooShort } guard password.count < 15 else { print("too long") HapticsManager.shared.vibrate(for: .error) throw ValidationError.tooLong } for character in password { guard character.isLetter else { HapticsManager.shared.vibrate(for: .error) throw ValidationError.invalidCharacterFound(character) } } } 

This is my enum:

enum ValidationError: Error { case noPass case tooShort case tooLong case invalidCharacterFound(Character) } 

And this is my enum extension and where the problem occurs:

extension ValidationError: LocalizedError { var errorDescription: String? { print("helloooooo") switch self { case .tooShort: print("TOO SHORT") return NSLocalizedString( "Your username needs to be at least 4 characters long", comment: "" ) case .tooLong: return NSLocalizedString( "Your username can't be longer than 14 characters", comment: "" ) case .invalidCharacterFound(let character): let format = NSLocalizedString( "Your username can't contain the character '%@'", comment: "" ) return String(format: format, String(character)) default: return "There was an error." } } } 

If I type a password that is too short I expect it to go into the tooShort case but it goes into the default case every time.

Any help would be appreciated.

1 Answer 1

1

The problem is this line:

guard password.count == 0 else { 

The count is never zero. So we fall into this else clause always! That is the .noPass throw.

throw ValidationError.noPass 

But your switch fails to handle that case so it runs the default.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I was wondering if that might have caused the issue but I didn't try it! Thanks for the insight.
Simple debugger usage would have solved it instantly. Learn to use the debugger.
Hah, yeah I should probably do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.