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
Here’s a basic solution to split the string and use part of it in the image name:
This does some very trivial validation (eg
count == 6
and it checks the prefix for10
), which you could make more stringent if you needed it, but this works for the basic task.Just get the last 4 digits, convert to integer, check if your desired range contains your value and check if they are all digits:
This will print