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?
>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.