我想知道是否可以动态获取 Swift 类型。例如,假设我们有以下嵌套结构:
struct Constants {
struct BlockA {
static let kFirstConstantA = "firstConstantA"
static let kSecondConstantA = "secondConstantA"
}
struct BlockB {
static let kFirstConstantB = "firstConstantB"
static let kSecondConstantB = "secondConstantB"
}
struct BlockC {
static let kFirstConstantC = "firstConstantBC"
static let kSecondConstantC = "secondConstantC"
}
}
可以从变量的 kSeconConstantC 中获取值)。喜欢:
let variableString = "BlockC"
let constantValue = Constants.variableString.kSecondConstantC
类似于NSClassFromString
, maybe?
不,这还不可能(至少作为一种语言功能)。
你需要的是你自己的类型注册表。即使使用类型注册表,您也无法获得static
常量,除非你有一个协议:
var typeRegistry: [String: Any.Type] = [:]
func indexType(type: Any.Type)
{
typeRegistry[String(type)] = type
}
protocol Foo
{
static var bar: String { get set }
}
struct X: Foo
{
static var bar: String = "x-bar"
}
struct Y: Foo
{
static var bar: String = "y-bar"
}
indexType(X)
indexType(Y)
typeRegistry // ["X": X.Type, "Y": Y.Type]
(typeRegistry["X"] as! Foo.Type).bar // "x-bar"
(typeRegistry["Y"] as! Foo.Type).bar // "y-bar"
类型注册表是使用自定义注册类型的东西Hashable
类型(比如说String
or an Int
)。然后,您可以使用此类型注册表来引用使用自定义标识符(aString
, 在这种情况下)。
Since Any.Type
本身并没有那么有用,我构建了一个接口Foo
通过它我可以访问静态常量bar
。因为我知道X.Type
and Y.Type
两者都符合Foo.Type
,我强制转换并阅读了bar
财产。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)