我想根据类型创建字符串(如果你必须知道的话,URL 的一部分)。
考虑这个示例代码:
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"
}
}
这看起来相当不错;我不需要依赖不安全的措施(字符串),也不需要单独的枚举。
让我们看一些用法示例:
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))")
}
虽然前两个函数很好(通用版本特别好!),但第三个不能编译:
错误:在参数类型中
TestQ.Protocol.Type
,TestQ.Protocol
不符合预期类型TestP
TestP.Type
也TestP.Protocol
不能作为参数工作。
如何将协议类型传递给(通用)函数?