Swift:如何从函数返回类的类型 [英] Swift: how to return class type from function
问题描述
func setGeneric< T>(type: T.Type){}
setGeneric(Int.self)
但是我们如何返回从函数中键入?写一些类似于
func getGeneric< T>() - > T.Type {
return Int.self
}
给编译器错误 Int与T不相同。那么是否有可能从swift函数返回类型?
编辑
一些解释。我有用于持久性的类(我使用Realm),并且我有类作为这个类的包装。所有包装都继承自 RealmClassWrapper
,它需要知道它实际包装的Realm类。所以我们可以说我有这个领域模型:
pre $ class $ RealmTodo RLMObject {
dynamic var title =
和我的包装supper类看起来像这样:
$ $ p $ class RealmClassWrapper {
private let backingModel:RLMObject
// ...
func backingModelType< T>() - > T.Type {fatalError(must be implemented)}
}
和实际的包装器:
class Todo:RealmClassWrapper {
//其他一些属性
func backingModelType< T>() - > T.Type {return RealmTodo.self}
}
你可以返回任何你想要的类型。
func getTypeOfInt() - > Int.Type {return Int.self}
func getTypeOfBool() - > Bool.Type {return Bool.self}
如果类型不是由参数确定的,或者返回的是不变的,不需要引入通用的 T
类型。
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.
这篇关于Swift:如何从函数返回类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!