gpt4 book ai didi

swift - Swift 中的泛型函数

转载 作者:行者123 更新时间:2023-11-28 14:31:21 25 4
gpt4 key购买 nike

我一直在搜索,但我找到的大多数答案都比我目前所能理解的要复杂。如果那里有教程,我将不胜感激,但这是我的问题:

我有多个函数,它们具有相同的机制和形式,但调用不同的类。现在,我重复了很多相同的代码,我想有一种更短的方法可以做到这一点。这是一个例子:

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:
()
}

处理这些情况的最佳方法是什么?

最佳答案

这似乎与泛型没有任何关系。这似乎只是一个强制执行 DRY 的重构问题(不要重复你自己)。

  • 如果想法是 ownershipQuestionListdiscomfortQuestionListresourceQuestionList 都需要有某些共同的属性,那么让它们有同一类,或者是同一类的子类,或者是共同协议(protocol)的采用者。

  • 如果他们已经这样做了,那么只需将公共(public)代码移到本地函数中,然后每次都调用它。

关于swift - Swift 中的泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51227653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com