Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check the string doesn’t contain any letters in swift?

i have trouble during making the letter checker, my code is like this: if !containLetters(“1234h”){print(“pass”)}

my function is

    func containsOnlyNum(input: String) -> Bool {
         var ok = false
         for chr in input {
             for check in "1234567890.-"{
                if chr == check{
                    ok = true
                }
             }
             if ok != true{
                 return false
             }
         }
         return true
    }

If I check for “h” then didn’t pass, but if i check for ”1h” then it still pass! Please help me to fix this problem. I will give a big thank for anyone who helped me

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The simplest way to fix the algorithm is this way:

func containsOnlyNum(input: String) -> Bool {
     // check every character
     for chr in input {
         var isNum = false
         
         for check in "1234567890.-"{
            if chr == check {
                isNum = true
                // if we have found a valid one, we can break the iteration
                break
            }
         }
         
         if !isNum {
             return false
         }
     }
    
     return true
}


print(containsOnlyNum(input: "1234")) // true
print(containsOnlyNum(input: "1234h")) // false

However, then you can directly simplify it to:

func containsOnlyNum(input: String) -> Bool {
    return input.allSatisfy { chr in
        "1234567890.-".contains(chr)
    }
}

which does exatly the same but uses allSatisfy and contains functions, which represent the logical operators ALL and EXISTS.

However, programmers normally use regular expressions for similar tasks:

func containsOnlyNum(input: String) -> Bool {
    return input.range(of: "^[0-9.\\-]+$", options: .regularExpression) != nil
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading