是否可以从字符串中获取 Swift 类型?

RFG*_*RFG 4 struct swift

我想知道是否可以动态获取 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"
  }
}
Run Code Online (Sandbox Code Playgroud)

可以从变量的 kSeconConstantC 中获取值)。喜欢:

let variableString = "BlockC"
let constantValue = Constants.variableString.kSecondConstantC
Run Code Online (Sandbox Code Playgroud)

NSClassFromString也许是类似的东西?

Vat*_*not 6

不,这还不可能(至少作为一种语言功能)。

您需要的是您自己的类型注册表。即使使用类型注册表,您也无法获取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"
Run Code Online (Sandbox Code Playgroud)

类型注册表是使用自定义Hashable类型(例如 aString或 an Int)注册类型的东西。然后,您可以使用此类型注册表来引用使用自定义标识符(String在本例中为 a )的已注册类型。

由于Any.Type其本身并不是那么有用,因此我构建了一个接口,Foo通过它我可以访问静态常量bar。因为我知道X.Type并且Y.Type两者都符合Foo.Type,所以我强制进行强制转换并阅读该bar属性。