1
\$\begingroup\$

I would like to use this same code on multiple pages of photos (to help my son recognize people). So instead of reinserting the name of each person, I created the appearingInPhoto (tuple or array), so I can utilize just .a .b .c, instead of having to go and rename each line of code.

Is there a way to simplify the code further, so I can just have code that checks if a button is pressed (check that sender.currentTitle is equal to any of the tuple values) and if yes, run this code?

print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a

This is the full function now:

var appearingInPhoto = (a:"omar", b:"john", c:"thomas")

@IBAction func buttonPressed(_ sender: UIButton) {
    var soundName: String? = nil
    if sender.currentTitle == appearingInPhoto.a {
        print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a
    }else if sender.currentTitle == appearingInPhoto.b {
        print("pressed \(appearingInPhoto.b)")
        label.text = appearingInPhoto.b
        soundName = appearingInPhoto.b
    }else if sender.currentTitle == appearingInPhoto.c {
        print("pressed \(appearingInPhoto.c)")
        label.text = appearingInPhoto.c
        soundName = appearingInPhoto.c
    }
    if let soundName = soundName {
        playSoundFile(soundName)
    }
  }
\$\endgroup\$
  • \$\begingroup\$ You're using the wrong data type. You want an array, not a dictionary. var appearingInPhoto:[String] = ["omar","john","thomas"]Then loop over it \$\endgroup\$ – Snowbody Jan 12 '18 at 22:36
  • 1
    \$\begingroup\$ I feel that you need a model to save all information related to the user that you will show. Also detecting the appearing person by comparing the text of the button is not considered safe. if you can describe more what you want top achieve or a screenshot of the screen that you have implanted to understand the context then we can help to improve the implementation \$\endgroup\$ – iOSGeek Jan 16 '18 at 20:30
1
\$\begingroup\$

Slightly modified (using array):

var appearingInPhoto = ["omar", "john", "thomas"]

@IBAction func buttonPressed(_ sender: UIButton) {

    guard let soundName = sender.currentTitle else {
        return
    }
    if appearingInPhoto.contains(soundName) {
        print("pressed \(soundName)")
        label.text = soundName
        playSoundFile(soundName)
    }

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.