gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:59:30 25 4
gpt4 key购买 nike

我想知道是否可以动态获取 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 的东西?

最佳答案

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

您需要的是您自己的类型注册表。即使使用类型注册表,您也无法获得 static 常量,除非您有相应的协议(protocol):

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 类型(例如 StringInt)注册您的类型的东西。然后,您可以使用此类型注册表来引用使用自定义标识符(在本例中为 String)的已注册类型。

由于 Any.Type 本身并不是那么有用,我构造了一个接口(interface) Foo,通过它我可以访问静态常量 bar。因为我知道 X.TypeY.Type 都符合 Foo.Type,所以我强制转换并读取了 bar 属性。

关于swift - 是否可以从字符串中获取 Swift 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37318897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com