Reputation: 598
Is it possible to pass a class as a function parameter? I currently have a base class which I'll refer to as BaseClass
. Right now, here's what I can do:
func someFunction(instanceParameter: BaseClass) {
// code
}
The parameter would be some class that inherits from BaseClass
. However, I would like to pass a class type itself as a parameter. Here's some pseudo-code:
func someFunction(classParameter: Class) {
// code
}
The parameter would be ClassThatInheritsFromBaseClass
instead of an instance of ClassThatInheritsFromBaseClass
.
On top of that, would it be possible to restrict the class parameter to classes that inherit from BaseClass
? The pseudo-code below shows what I mean.
func someFunction(classParameter: BaseClass_Class_Not_Instance) {
// code
}
Upvotes: 4
Views: 116
Reputation: 37053
You're looking for the metatype type - .Type
:
func someFunction(classParameter: Class.Type) {
// code
}
You may be able to restrict to only subclasses using generics, but I haven't tested this just yet:
func someFunction<T: BaseClass where T != BaseClass>(classParameter: T.Type) { ... }
Upvotes: 2