简体   繁体   English

如何将协议类型传递给泛型函数?

[英]How can I pass protocol types to generic functions?

I want to create strings depending on types (parts of URLs, if you must know). 我想根据类型(部分URL,如果必须知道)创建字符串。

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 type TestP 错误:参数类型TestQ.Protocol.Type中的TestQ.Protocol与预期的类型TestP

TestP.Type and TestP.Protocol do not work as parameters, either. TestP.TypeTestP.Protocol也不用作参数。

How can I pass protocol types to a (generic) function? 如何将协议类型传递给(通用)函数?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM