简体   繁体   中英

Swift: how to return class type from function

I know it is possible to pass class type to a function in swift:

func setGeneric<T>(type: T.Type){ }
setGeneric(Int.self)

But how we can return type from function? Writing something like

func getGeneric<T>() -> T.Type {
   return Int.self
}

gives compiler error "Int is not identical to T". So is it possible to return type from a swift function?

Edit
Some explanation. I have classes that are used for persistence (I'm using Realm) and I have classes that acts as wrappers around this classes. All wrappers inherits from RealmClassWrapper which needs to know what Realm class it actually wraps. So lets say I have this realm model:

class RealmTodo: RLMObject {
   dynamic var title = ""
}

and my wrappers supper class looks like this:

class RealmClassWrapper {
   private let backingModel: RLMObject
   //...
   func backingModelType<T>() -> T.Type{ fatalError("must be implemented") }
}

and actual wrapper:

class Todo: RealmClassWrapper {
   //some other properties
   func backingModelType<T>() -> T.Type{ return RealmTodo.self }
}

You can return any type you want.

func getTypeOfInt()  -> Int.Type  { return Int.self  }
func getTypeOfBool() -> Bool.Type { return Bool.self }

If the type is not determined from arguments or if the return is constant, there is no need to introduce a generic T type.

It works when I modify your function like this:

func getGeneric<T>(object: T) -> T.Type {
    return T.self
}

getGeneric(0)    // Swift.Int

You can force the downcast (as!) as below

func getGeneric<T>() -> T.Type {
  return Int.self as! T.Type
} 

But out of the function scope, you need to indicate the returned type:

var t:Int.Type = getGeneric()

Yes, this is possible. The problem here is that you say your function returns a generic T.type , but you always return Int.type . Since T is not always an Int, the compiler raises an error.

If you don't want to specify the return type you can use AnyClass as it instead of a template parameter.

class A {}

class B {}

public enum ExampleEnum: String {
    case a
    case b
    
    func asClass() -> AnyClass {
        switch self {
        case .a:
            return A.self
        case .b:
            return B.self
        }
    }
}



let myGoal : AnyClass = ExampleEnum.a.asClass()

You can also avoid the final cast to AnyClass, but compiler will show you an error

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