简体   繁体   English

如何在Swift中获取泛型参数的运行时类型的全限定名?

[英]How can I get the fully qualified name of the runtime type of a generic parameter in Swift?

Eg, 例如,

func inject<P, D>(params: P, create: P -> D) {
    let type = String(D)
    // etc.
}

The technique above seems to work for any Swift type (including protocols), but unfortunately type does not contain the module name, just the type itself. 上面的技术似乎适用于任何 Swift类型(包括协议),但是不幸的是, type不包含模块名称,仅包含类型本身。 In other words, if D is Watusi and Watusi is in the Zing module, I want Zing.Watusi , not just Watusi . 换句话说,如果DWatusiWatusiZing模块中,则我需要Zing.Watusi ,而不仅是Watusi

Anyone know how to get the whole enchilada, for any Swift type passed as a generic parameter? 有谁知道如何获取作为通用参数传递的任何 Swift类型的整个墨西哥卷饼?

Ultimately, the purpose of this is to use the fully qualified type as a key in this dependency resolver implementation . 最终,此操作的目的是使用完全限定的类型作为此依赖关系解析程序实现中的键。

Note: Anton Bronnikov made an excellent suggestion below. 注意:以下是Anton Bronnikov的出色建议。 It's one I was aware of, but I should clarify that I need a public API for this, otherwise the app will be rejected and my client will be unhappy. 这是我所知道的,但我需要澄清一下,我需要一个公共 API,否则该应用将被拒绝,我的客户将不满意。

I think you can get closer to what you want with: 我认为您可以通过以下方式更接近您想要的:

func inject<P, D>(params: P, create: P -> D) {
    let type = _stdlib_getDemangledTypeName(D)
    // etc.
}

Above will produce almost the string you want except with "unnecessary" .Type in the end. 上面将产生几乎所有您想要的字符串,除了最后加上“不必要的” .Type

答案是String(reflecting: D.self) ,其中D是类型。

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

相关问题 在Swift中,如何获得变量的完全限定名称? - In Swift, how do you get the fully-qualified name of a variable? 如何将 nil 传递给 Swift 上的泛型类型参数? - How can I pass nil to generic type parameter on Swift? 如何使通用协议在 Swift 中不通用? 所以我可以将它用作参数类型 - How to make generic protocol not generic in Swift? So I can use it as parameter type Swift使用泛型重构:如何隐含泛型类型的运行时值? - Swift refactor with generics: how can I imply runtime values from the generic type? 如何确定Swift中函数的泛型参数类型是什么? - How can I determine what is the type of generic parameter type in function in Swift? 在Swift声明的类上使用NSClassFromString()需要完全限定的名称 - Using NSClassFromString() on a Swift declared class requires a fully qualified name 在 Swift 中获取泛型类型的名称(字符串) - Get the name (string) of a generic type in Swift Swift 在运行时构建泛型类型 - Swift build generic type at runtime 如何使我的通用参数符合 Swift 中的 OR 以及如何找到参数的构造? - How can I make my generic parameter conform to OR in Swift and how can I found the conformation of parameter? 如何快速使用通用类型处理不同类型? - How can I handle different types using generic type in swift?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM