1

I want to check if the first three characters entered in the UI Textfield are numbers. I could do this easily in Python, but for some reason in Swift it's a pain.

Here's my python if statements (which I want to 'translate' into swift as it works):

str = "123abc"                                                                  
if str.isdigit():                               
        if str[:3]:                         
            print(str)

and here's my swift code

@IBOutlet weak var input: UITextField!

@IBAction func checkBarcodeRegion(_ sender: UIButton)
    {
        let text: String = input.text!

        if text.prefix(3)
        {
           //if numeric
               //do something
        }
    }

Can't get this to work. Any help appreciated.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Possible duplicate of [What is the replacement for isDigit() for characters in Swift?](https://stackoverflow.com/questions/26351625/what-is-the-replacement-for-isdigit-for-characters-in-swift) – user1118321 Jan 26 '19 at 17:24

2 Answers2

3

Three alternatives:

Create an Int from the substring and check if for non-nil.

let isNumeric1 = Int(text.prefix(3)) != nil

Remove all digits from the substring with Regular Expression and check for empty string

let isNumeric2 = text.prefix(3).replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression).isEmpty

Split the substring by the decimalDigits character set and check if the number of components is 4

let isNumeric3 = text.prefix(3).components(separatedBy: .decimalDigits).count == 4
vadian
  • 274,689
  • 30
  • 353
  • 361
1

Using prefix is the right direction to go. You can use allSatisfy after that to check if they are all digits. One of the ways to check for digits is to check if the unicode scalar is in the CharacterSet.decimalDigits set.

text.unicodeScalars.prefix(3)
    .allSatisfy(CharacterSet.decimalDigits.contains)

This will check for all the digits in Unicode, including the ones that the Indians and Arabic use.

If by digits you mean the ASCII 0123456789, then you could use:

text.prefix(3).allSatisfy(("0"..."9").contains)
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • No need to use a closure `text.unicodeScalars.prefix(3) .allSatisfy(CharacterSet.decimalDigits.contains)` and `text.prefix(3).allSatisfy( ("0"..."9").contains)` – Leo Dabus Jan 26 '19 at 18:31
  • 1
    @LeoDabus I guess that's a bit shorter. Edited. – Sweeper Jan 26 '19 at 18:32