简体   繁体   English

如何在泛型中返回闭包

[英]How to return closure in the generic

Now I using Realm to create a singleton , but I faced a problem, if I want to return a closure in the generic , and there are different types (Ex:.Case type return [Case], .Product type return [Product]), but I have no idea to implement this fuction. 现在,我使用Realm创建一个singleton ,但是如果我想返回genericclosure ,并且遇到了不同的类型(例如:.Case类型return [Case] 、. Product类型return [Product]),我遇到了一个问题。 ,但我不知道要实现此功能。 Could anyone help me with this problem?Thanks! 有人可以帮助我解决这个问题吗?

DataType: 数据类型:

enum DataType{
    case Case
    case Product
    case Category
    case Composition
} 

fetchItem fuction: 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
    }
}

Templating a function is the class that you want to get. 模板函数是您要获取的类。 Let's take for exemple this function 让我们以这个功能为例

func showTemplate<T>(myVariable: T) {
   print(myVariable)
}

Here, if I want to call the showTemplate function I must do it with the type I want : 在这里,如果要调用showTemplate函数,则必须使用所需的类型来执行此操作:

showTemplate<String>() # print a string
showTemplate<Int>() # print a int
showTemplate<myClass> # print a myClass

So you are having a problem, but in the wrong way because with templating, you HAVE to know the class before you call the function. 因此,您遇到了问题,但是方式错误,因为使用模板,您必须在调用函数之前先了解类。

You can for example try to use inheritance and templating your motherClass with your wanted class. 例如,您可以尝试使用继承并将模板与所需的类一起模板化。

class wantedClass {
   var myCaseVariable: Case
   var myProductVariable: Product
   var myThingsVariable: Things

   init() {
   }

   fillClass<T: Case>() {
   // set case
   } 

   // Etc etc
}

Moreover, I don't think that templating is the good solution here, I suggest to look at this : Using a Type Variable in a Generic 此外,我认为模板不是这里的好解决方案,我建议您看一下: 在泛型中使用类型变量

I believe you cannot do this for completely different types in one place using only generic type (not any class-holders or so). 我相信您不能在一处仅使用通用类型(而不是任何类持有者)对完全不同的类型执行此操作。 Maybe you should create separate funcs for each item ( fetchCaseItems() , fetchProductItems , etc.). 也许您应该为每个项目( fetchCaseItems()fetchProductItems等)创建单独的功能。 It's much clear to read and every func is responsible only for its own data type. 读起来很清楚,每个func仅负责其自己的数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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