aehlke aehlke - 1 year ago 62
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
type is
or not inside its initializer.

I've tried a variety of things like trying to cast to
(the Swift compiler allows it but tells me this always fails), or using
, but I'm missing something fundamental here.

How can I check whether the generic type is

Answer Source

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) {
        } else {
            print("Not Void!")

// Will print Not Void
var test = MyClass<Int>()

// Will print Void
var test2 = MyClass<Void>()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download