Duncan Groenewald
Duncan Groenewald

Reputation: 9018

What is wrong with this Swift syntax?

I can't figure out what is wrong with the following:

fileprivate func showInlineErrorMessage(_ message: String, forField textField: UITextField) {

        // Show error message
        errorLabel.text   = message
        errorLabel.isHidden = false

        // Highlight field on which the error is
        [usernameTextField, passwordTextField, birthYearTextField, genderTextField].forEach {
            updateHighlightOnTextField($0!, highlight: $0 === textField )
        }
    }

The specific part is $0 === textField

The compiler is showing the following error:

"?" must be followed by a call, member lookup, or a subscript

This is old code, so it seems something may have changed recently.

The called function is

fileprivate func updateHighlightOnTextField(_ textField: UITextField, highlight: Bool) {
        let highlightView = textField.superview!
        highlightView.layer.borderWidth = highlight ? 1.0 : 0.0
        highlightView.layer.borderColor = highlight ? DefaultTheme.lineColorError.cgColor : nil
    }

enter image description here

Upvotes: 1

Views: 114

Answers (2)

Jacolack
Jacolack

Reputation: 1508

Sometimes swift cannot understand the type of an inline statement. Have you tried:

Creating an external Boolean:

    [usernameTextField, passwordTextField, birthYearTextField, genderTextField].forEach {
        let isHighlighted: Bool = ($0 === textField)
        updateHighlightOnTextField($0!, highlight: isHighlighted)
    }

Upvotes: 1

rmaddy
rmaddy

Reputation: 318955

The needless use of the force-unwrapping seems to be causing the problem.

If you change:

updateHighlightOnTextField($0!, highlight: $0 === textField)

to:

updateHighlightOnTextField($0, highlight: $0 === textField)

then the problem goes away.

This does assume that your text field properties are declared as either non-optional or as implicitly unwrapped optionals.

In the unlikely event that your text fields are declared as optionals then you can safely unwrap $0 to avoid the use of !.

Upvotes: 1

Related Questions