test for string length Swift 3

I want to test for the length of a string in a UITextField, and return false if it's either nil or "" (empty string), and true otherwise.

In ObjC, this would be a simple line of code

Bool isnotempty = myTextField.text.length != 0


In earlier versions of Swift 3, I was doing

let isnotempty = myTextField.text?.characters.count > 0


In the latest Swift 3 (Xcode 8.0 beta 6), the above code now returns an optional Int from "count", and i have to change it to this to make the compiler happy

let isnotempty = myTextField.text != nil && myTextField.text!.characters.count > 0


This is terrible! How many hoops does one have to jump through to test for a string containing some text? Is there a better way to do it that I'm missing?

Thanks,

LMY

Answered by OOPer in 171192022

I would write it as:

let isnotempty = !(myTextField.text?.isEmpty ?? true)


And the title of your question is not appropriate. You have no need to count exact length of the String, when you just want to check if it's empty or not.

Accepted Answer

I would write it as:

let isnotempty = !(myTextField.text?.isEmpty ?? true)


And the title of your question is not appropriate. You have no need to count exact length of the String, when you just want to check if it's empty or not.

nice! thanks!!

test for string length Swift 3
 
 
Q