Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function that checks if a variable is of type that is passed as parameter in swift

I’d like to write a function that will either doSomething() or doSomethingElse() depending on whether a passed parameter a is of type B. Where B is passed as a second parameter to that function.

My attempt:

func magic<T>(a: Any, b: T.Type) {
    if a is b {
        doSomething()
    } else {
        doSomethingElse()
    }
}

Is that even possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The syntax would be:

func magic<T>(a: Any, b: T.Type) {
    if a is T {
        doSomething()
    } else {
        doSomethingElse()
    }
}

💡 But maybe generic is not what you need here. You can have multiple overloads instead:

func magic(someType: SomeType) {
    // do Something
}

func magic(someOtherType: SomeOtherType) {
    // do Something else
}

This way you can be sure about the type at the compile time instead of run-time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading