0

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. Could anyone help me with this problem?Thanks!

DataType:

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

fetchItem fuction:

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
    }
}
廖豪豪
  • 93
  • 9

2 Answers2

1

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<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

Sacha.R
  • 394
  • 2
  • 17
0

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.). It's much clear to read and every func is responsible only for its own data type.

pacification
  • 5,838
  • 4
  • 29
  • 51