Binary operator '>=' cannot be applied to operands of type 'String.IndexDistance?' (aka 'Optional<Int>') and 'Int'

Viewed 10147

in Swift 4 I'm trying to compare the length of the text of an UITextField with a minimum length:

if textFieldPassword.text?.count >= 8 {        
}

but i'm getting the error

Binary operator '>=' cannot be applied to operands of type 'String.IndexDistance?' (aka 'Optional<Int>') and 'Int'


Ironically it works with

textFieldPassword.text?.count == 8

Can somebody help me?

1 Answers

The reason is that Equatable works with optionals and Comparable does not. You have to unwrap the optional.

A suitable and safe solution is to optional bind the text property:

if let password = textFieldPassword.text, password.count >= 8 { ... }
Related