0

我想根据类型创建字符串(如果你必须知道的话,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.TypeTestQ.Protocol不符合预期类型TestP

TestP.TypeTestP.Protocol不能作为参数工作。

如何将协议类型传递给(通用)函数?

4

1 回答 1

-2
protocol TestP {
    var p: Int { get }
}
protocol TestQ: TestP {
    var q: Int { get }
}
struct TestR: TestQ {
    var p = 1
    var q = 2
}

struct TestS: TestP
{
    var p = 42
}

func toDescription<T: TestP>(type: T.Type) -> String
{
    switch type
    {
    case let x where x == TestR.self:
        return "Arrr"
    default:
        return "Unsupported"
    }
}

print (toDescription(type: TestR.self)) // Arrr
print (toDescription(type: TestS.self)) // Unsupported
于 2017-02-28T15:57:46.263 回答