I have a situation like so:
protocol Vehicle {} struct Car: Vehicle, Decodable {} func doSomethingWith<T>(type: T.Type) { if let vehicle = type as? Vehicle.Type { print("Nice, I detected that my type was a vehicle: \(vehicle)") } else { print("Ah, my type is a vehicle wrapped in an optional! \(type)") } } and I call it with:
doSomethingWith(type: Car.self) doSomethingWith(type: Car?.self) It will output:
Nice, I detected that my type was a vehicle: Car Ah, my type is a vehicle wrapped in an optional! Optional<Car> This is surprising to me. I would expect let vehicle = type as? Vehicle.Type to work in both calls to doSomethingWith, but because the second call passes an optional, my doSomethingWith function is unable to determine that this type conforms to Vehicle protocol. It makes sense, since the Optional class doesn't conform to it, the wrapped element in my optional does.
Is there some way I can modify doSomethingWith to (optionally) extract the inner type if an optional is passed to it such as in my second example?