簡體   English   中英

如何將協議類型傳遞給泛型函數?

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

我想根據類型(部分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.TypeTestP.Protocol也不用作參數。

如何將協議類型傳遞給(通用)函數?

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