aehlke aehlke - 6 months ago 19
Swift Question

How to check if a Swift generic type is Void?

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
?

Answer

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>()