【问题标题】:How verify a string having only numbers and a decimal(dot) using swift如何使用swift验证只有数字和小数(点)的字符串
【发布时间】:2022-08-18 18:57:16
【问题描述】:

我有一个文本框,如果我输入一个数字,它应该将该数字转换为十进制数字,例如,如果

  • 我输入 56 然后点击验证按钮,它将转换并显示 56.0
  • 我输入 56.0 然后点击验证按钮,它将转换并显示 56.0

所以在这里我需要验证转换后的值 56.0 现在是否是十进制数,如果是,可以通过检查 string.contains(\".\") 然后使用下面的代码将其拆分为 \".\"

let enteredValue = \"56.0\"
enteredValue.components(separatedBy: \" \")
        let expectedEnteredValueLastPart = array.last!
enteredValue.components(separatedBy: \" \")
        let expectedEnteredValueFirstPart = array.first!

现在我有第一部分 \"56\" 和第二部分 \"0\" 使用正则表达式如何验证这两个部分只包含数字。 enter image description here

  • 无需使用正则表达式,您只需使用expectedEnteredValueFirstPart.allSatisfy({\"0\"...\"9\" ~= $0})
  • 我通常会建议停止使用正则表达式并尝试使用NumberFormatter 解析该数字。

标签: swift string decimal number-formatting


【解决方案1】:

你可以做这样的事情

 extension String {
    var isNumeric: Bool {
        guard self.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self).isSubset(of: nums)
    }
}

var enteredValue = "56.0"

var firstPart = enteredValue.components(separatedBy: ".").first!
var secondPart = enteredValue.components(separatedBy: ".").last!

if firstPart.isNumeric && secondPart.isNumeric {
    //do something
}

我建议使用 UITextFieldDelegateUITextViewDelegate 来限制字符。

【讨论】:

    猜你喜欢
    • 2016-02-16
    • 1970-01-01
    • 2014-09-10
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多