-7

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)])
            }
    }
Community
  • 1
  • 1
J A S K I E R
  • 1,976
  • 3
  • 24
  • 42
  • 1
    reformat your question. it showing `[![enter image description here][1]][1]` – Klevison May 16 '16 at 16:34
  • You need to learn about optional values http://stackoverflow.com/q/24003642/1959140 – Gaurav Sharma May 16 '16 at 16:38
  • Possible duplicate of [Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' Using Parse In Swift 2.0](http://stackoverflow.com/questions/33159412/value-of-optional-type-string-not-unwrapped-did-you-mean-to-use-or-u) – Slayter May 16 '16 at 16:40

2 Answers2

2

The problem here is that you are trying to apply the method "isEmpty" to an optional-wrapped string "textfield.text".

You should replace your if statement with the following:

if textField.text?.isEmpty || count(textField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))

text is optional in textfield because a textfield's text can be nil! Watch out for these cases when unwrapping optional objects!

If you want to provide a base case you could to something like this:

let text = textfield.text? ?? ""

Then you can replace all occurrences of textfield.text with this variable and be sure it will never be nil!

Caio Tomazelli
  • 513
  • 5
  • 14
1

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.

CodeReaper
  • 5,988
  • 3
  • 35
  • 56