【问题标题】:pattern.firstMatch is get Error : Expression type '@lvalue String?' is ambiguous without more contextpattern.firstMatch 得到错误:表达式类型'@lvalue String?'没有更多上下文是模棱两可的
【发布时间】:2019-09-07 20:53:29
【问题描述】:

我是第一个 iPhone 开发者。我想要做的是区分文本字段中的特殊字符。所以我尝试使用正则表达式。但它向我显示了错误。

    @IBOutlet weak var walletNameField: UITextField!

    @IBAction func nextButtonFuc(_ sender: UIButton) {
        let pattern = try! NSRegularExpression(pattern: "^[a-zA-Z0-9가-힣ㄱ-하-ㅣ\\s]$", options: .caseInsensitive)
        if walletNameField.text!.isEmpty {
            callAlert("test")
        } else if walletPasswordField.text!.isEmpty {
            callAlert("test")
        } else if confirmField.text!.isEmpty {
            callAlert("test")
        } else if walletPasswordField.text != confirmField.text {
            callAlert("test")
        } else if walletNameField.text!.count > 10 {
            callAlert("test")
        } else if walletPasswordField.text!.count  < 8 ||
            walletPasswordField.text!.count >= 20 {
            callAlert("test")
        } else if pattern.firstMatch(in: "\(walletNameField.text!)", options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, walletNameField.text!.count)) { //get Error Expression type '@lvalue String?' is ambiguous without more context
            callAlert("test")
        }
    }

错误是

表达式类型'@lvalue String?'没有更多上下文是模棱两可的

我做错了什么?我觉得这个问题很难解决。

当我触摸任何地方时,我都会尝试隐藏我的键盘。但是,函数本身是一个错误。为什么会出错?

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }

// Error is  Declaration 'touchesBegan(touches:withEvent:)' has different argument labels from any potential overrides

提前致谢

【问题讨论】:

  • firstMatch 不返回 Bool

标签: ios swift pattern-matching


【解决方案1】:

您需要将 firstMatch 与一个值进行比较,因为 if 需要一个 BOOL

} else if pattern.firstMatch(in: "\(walletNameField.text!)", options: NSRegularExpression.MatchingOptions.reportCompletion,range: NSRange(location:0,length:walletNameField.text!.count)) != nil  {  

}

或使用if let

} else if let first =  pattern.firstMatch(in: "\(walletNameField.text!)", options: NSRegularExpression.MatchingOptions.reportCompletion,range: NSRange(location:0,length:walletNameField.text!.count))  {  
   print(first)
}

升级touchesBegan你需要使用最新的语法Here

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

【讨论】:

  • 谢谢。 @Sh_Khan 你能告诉我是否有更简单的方法来解决这个问题而不使用正则表达式?例如特殊字符+数字+无字母或特殊字符
  • 在文本字段中输入特殊字符不会显示警报。我认为正则表达式是错误的。有什么问题?
【解决方案2】:

在您的第二个问题中,即隐藏键盘,功能应该是:-

   override func touchesBegan(touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多