Finding out whether a string is numeric or not

前端 未结 18 1655
一个人的身影
一个人的身影 2020-12-07 15:24

How can we check if a string is made up of numbers only. I am taking out a substring from a string and want to check if it is a numeric substring or not.

NSS         


        
18条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 15:50

    The easiest and most reliable way is trying to cast as Double, if the result is nil - it can't be formed into a legit number.

    let strings = ["test", "123", "123.2", "-123", "123-3", "123..22", ".02"]
    let validNumbers = strings.compactMap(Double.init)
    
    print(validNumbers)
    // prints [123.0, 123.2, -123.0, 0.02]
    

    More info in the documentation: https://developer.apple.com/documentation/swift/double/2926277-init

提交回复
热议问题