我想知道是否可以动态获取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"
}
}
它可以从一个变量从kSeconConstantC获得价值)。像:
let variableString = "BlockC"
let constantValue = Constants.variableString.kSecondConstantC
东西类似NSClassFromString
,也许?
值不能用作标识符,根据我的想法我认为这是不可能的 –
你可以使用像if(variableString ==“BlockC”)然后做点什么 –
谢谢你的赞扬,但背后的想法是减少码。我更喜欢(如果存在)解决方案,而不是为每个案例写几个if-else。 – RFG