Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Swift generic type is Void?

Tags:

generics

swift

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?

like image 466
aehlke Avatar asked May 19 '16 03:05

aehlke


1 Answers

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>()
like image 101
Carter Avatar answered Sep 28 '22 07:09

Carter