ios Swift:如何从函数返回类类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29196463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: how to return class type from function
提问by Nikita Arkhipov
I know it is possible to pass class type to a function in swift:
我知道可以在 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?
给出编译器错误“Int 与 T 不同”。那么是否可以从 swift 函数返回类型?
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:
编辑
一些解释。我有用于持久性的类(我使用的是 Realm),并且我有一些类充当这些类的包装器。所有包装器都继承自RealmClassWrapper
它们,需要知道它实际包装的是哪个 Realm 类。所以可以说我有这个领域模型:
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 }
}
回答by GoZoner
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.
如果类型不是由参数确定的,或者如果返回是常量,则无需引入泛型T
类型。
回答by Eric Aya
It works when I modify your function like this:
当我像这样修改你的函数时它会起作用:
func getGeneric<T>(object: T) -> T.Type {
return T.self
}
getGeneric(0) // Swift.Int
回答by jcnm
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()
回答by Rengers
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.
是的,这是可能的。这里的问题是你说你的函数返回一个泛型T.type
,但你总是返回Int.type
。由于 T 并不总是一个 Int,编译器会引发错误。