简体   繁体   中英

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
    }

在此处输入图片说明

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)
    }

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 ! .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM