现在我使用 Realm
创建一个 singleton
,但是我遇到了一个问题,如果我想在 中返回一个
,并且有不同的类型(例如:.Case type return [Case],.Product type return [Product]),但我不知道如何实现这个功能。
谁能帮我解决这个问题?谢谢!closure
>generic
数据类型:
enum DataType{
case Case
case Product
case Category
case Composition
}
fetchItem 函数:
func fetchItem<T>(type: DataType,complete:@escaping ([T]) -> ()) {
var list:[T]? = []
switch type {
case .Case:
let realm = try! Realm()
let caseResult = realm.objects(Case.self)
caseResult.forEach { (item) in
...
}
complete([])
return
case .Product:
return
case .Category:
return
case .Composition:
return
}
}
最佳答案
模板化一个函数就是你想要得到的类。 让我们以这个功能为例
func showTemplate<T>(myVariable: T) {
print(myVariable)
}
在这里,如果我想调用 showTemplate 函数,我必须使用我想要的类型来调用它:
showTemplate<String>() # print a string
showTemplate<Int>() # print a int
showTemplate<myClass> # print a myClass
所以你遇到了问题,但方式不对,因为使用模板,你必须在调用函数之前了解类。
例如,您可以尝试使用继承并使用您想要的类对您的 motherClass 进行模板化。
class wantedClass {
var myCaseVariable: Case
var myProductVariable: Product
var myThingsVariable: Things
init() {
}
fillClass<T: Case>() {
// set case
}
// Etc etc
}
此外,我不认为模板是这里的好解决方案,我建议看看这个:Using a Type Variable in a Generic
关于ios - 如何在通用中返回闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48113876/