I have a class along these lines: class MyClass<Input>
and I would like to check whether the Input
type is Void
or not inside its initializer.
I've tried a variety of things like trying to cast to Void
(the Swift compiler allows it but tells me this always fails), or using is
, but I'm missing something fundamental here.
How can I check whether the generic type is Void
?
You can do this by comparing the .self
values of the generic variable and Void
. Here's a quick example that you can stick in a Swift playground to see it work!
import UIKit
class MyClass<T> {
init() {
if(T.self == Void.self) {
print("Void!")
} else {
print("Not Void!")
}
}
}
// Will print Not Void
var test = MyClass<Int>()
// Will print Void
var test2 = MyClass<Void>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With