skip to Main Content

I’m writing a check in app for my gym in XCode. I asked this a year and a half ago for Android: Is there a way around doing 2000 else if statements in this?

But now, I am reaching 2000 members and need to add more. Unfortunately, and obviously, Xcode is crashing when I try to add more lines.

My code is this:

    @IBAction func displayBarcode(_ sender: UIButton) {
        if nameTextField.text=="100001" {
            imageView.image = UIImage(named: ("All Barcodes/a0001.jpg"));  
        }    
        else if nameTextField.text=="100002" { imageView.image = UIImage(named: ("All Barcodes/a0002.jpg"));}
        else if nameTextField.text=="100003" { imageView.image = UIImage(named: ("All Barcodes/a0003.jpg"));}
        else if nameTextField.text=="100004" { imageView.image = UIImage(named: ("All Barcodes/a0004.jpg"));}
        else if nameTextField.text=="100005" { imageView.image = UIImage(named: ("All Barcodes/a0005.jpg"));}

…all the way down to 2000. I know, absolutely crazy, but it has worked. Is there a way to combine these into one if/else statement into a range, similar to the solution someone gave me for Android?

Thank you sincerely!

2

Answers


  1. Here’s a basic solution to split the string and use part of it in the image name:

    @IBAction func displayBarcode(_ sender: UIButton) {
        guard let input = nameTextField.text else {
            return
        }
        guard input.count == 6, input.prefix(2) == "10" else {
            return
        }
        let imageName = "All Barcodes/a(input.suffix(4)).jpg"
        if let image = UIImage(named: imageName) {
            imageView.image = image
        }
    }
    

    This does some very trivial validation (eg count == 6 and it checks the prefix for 10), which you could make more stringent if you needed it, but this works for the basic task.

    Login or Signup to reply.
  2. Just get the last 4 digits, convert to integer, check if your desired range contains your value and check if they are all digits:

    let string = "100002"
    let suffix = string.suffix(4)
    let range = 1...2000
    if let int = Int(suffix),
        suffix.count == 4,
        suffix.allSatisfy(("0"..."9").contains),
        range ~= int {
        let imageName = "All Barcodes/a(suffix).jpg"
        print(imageName)
    }
    

    This will print

    All Barcodes/a0002.jpg

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search