代码之家  ›  专栏  ›  技术社区  ›  Duncan Groenewald

这个Swift语法有什么错?

  •  1
  • Duncan Groenewald  · 技术社区  · 9 年前

    我想不出以下是怎么回事:

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

    具体部分是 $0 === textField

    编译器显示以下错误:

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

    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

    2 回复  |  直到 9 年前
        1
  •  1
  •   Jacolack    9 年前

    有时swift无法理解内联语句的类型。 您是否尝试过:

        [usernameTextField, passwordTextField, birthYearTextField, genderTextField].forEach {
            let isHighlighted: Bool = ($0 === textField)
            updateHighlightOnTextField($0!, highlight: isHighlighted)
        }
    
        2
  •  1
  •   rmaddy    9 年前

    不必要地使用力展开似乎是造成问题的原因。

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

    收件人:

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

    然后问题就消失了。

    这确实假设您的文本字段属性声明为非可选或隐式展开的可选。

    $0 避免使用 ! .