简体   繁体   中英

Generic functions in Swift

I've been searching but most answers I've found are more complex than I can currently understand. If there is a tutorial out there I'd appreciate a link, but here is my question:

I have multiple functions that have the same mechanics and form, but call different classes. Right now, I repeat a lot of the same code and I imagine there's a shorter way to do this. Here is an example:

func nextQuestion() {

    switch analysisProgress {
    case 7:

        if questionProgress < ownershipQuestionList.list.count {
            questionLabel.fadeTransition(0.4)
            questionLabel.text = ownershipQuestionList.list[questionProgress].question
            definitionText.text = ownershipQuestionList.list[questionProgress].definitions
            } else {
                self.performSegue(withIdentifier: "goToNarrativeVC", sender: nil)
            }

    case 9:

        if questionProgress < discomfortQuestionList.list.count {
            questionLabel.fadeTransition(0.4)
            questionLabel.text = discomfortQuestionList.list[questionProgress].question
            definitionText.text = discomfortQuestionList.list[questionProgress].definitions
            } else {
                self.performSegue(withIdentifier: "goToNarrativeVC", sender: nil)
            }

    case 10:

        if questionProgress < resourceQuestionList.list.count {
            questionLabel.fadeTransition(0.4)
            questionLabel.text = resourceQuestionList.list[questionProgress].question
            definitionText.text = resourceQuestionList.list[questionProgress].definitions
        } else {
            self.performSegue(withIdentifier: "goToNarrativeVC", sender: nil)
        }

    default:
        ()
    }

What's the best way to handle these situations?

This doesn't seem to have anything to do with generics. It seems to be merely a matter of refactoring to enforce DRY (don't repeat yourself).

  • If the idea is that ownershipQuestionList and discomfortQuestionList and resourceQuestionList all need to have certain properties in common, then make them have the same class, or be subclasses of the same class, or be adopters of a common protocol.

  • If they already do that, then just move the common code off into a local function and call it each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM