Swift Question

Swift 2.0 How to unwrap in check?

I have found a topic but it seems it's not the same ...
Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' Using Parse In Swift 2.0

i have an error


Value of optional type 'String?' not unwrapped; did you mean to use
'!' or '?'?


func textFieldDidEndEditing(textField: UITextField)
{
if textField.text.isEmpty || count(textField.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))
== 0
{
textField.attributedPlaceholder = NSAttributedString(string: Messages.conversationNamePlaceholder.rawValue,
attributes:[NSForegroundColorAttributeName: UIColor.blackColor().colorWithAlphaComponent(0.54)])
}
}

Answer

The ! sign should be avoid, therefore I normally go for something like this:

if textField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).characters.count > 0 {
    ...
}

Using the ! unwraps an optional value, but if the value is nil, a fatal error will crash your app.