I want to create strings depending on types (parts of URLs, if you must know).
Consider this exemplary code:
import Foundation
protocol TestP {
var p: Int { get }
}
protocol TestQ: TestP {
var q: Int { get }
}
struct TestR: TestQ {
var p = 1
var q = 2
}
func toDescription<T: TestP>(type: T.Type) -> String {
switch type {
case is TestR.Type: return "Arrrr"
default: return "unsupported"
}
}
This seems reasonably nice; I didn't need to rely on unsafe measures (strings) nor did I need a separate enum.
Let's look at some usage example:
func example1<T: TestP>(val: T) {
print("Processing \(toDescription(type: T.self))")
}
func example2() {
print("Processing \(toDescription(type: TestR.self))")
}
func example3() {
print("Processing \(toDescription(type: TestQ.self))")
}
While the first two functions are fine (the generic version is particularly nice!), the third does not compile:
Error: in argument type
TestQ.Protocol.Type
,TestQ.Protocol
does not conform to expected typeTestP
TestP.Type
and TestP.Protocol
do not work as parameters, either.
How can I pass protocol types to a (generic) function?