我有一些枚举值,我想强制转换为JSONDecoder可解码的.Protocol类型
decode
方法。
每个属性枚举对应于
Codable
班级。
enum Attributes : String {
case Shapes = "GetShapes"
case Color = "GetColors"
case Size = "GetSizes"
}
我想我可以动态地将
例如
let results = try? JSONDecoder().decode(GetShapes.self, from: jsonData)
GetShapes.self
,对应于
枚举的值。
所以我试着用
NSProtocolFromString
但这似乎不管用。
if let protoRef = NSProtocolFromString(anAttribute.rawValue) {
if let results = try? JSONDecoder().decode(protoRef, from: jsonData) {
//Do something
}
能够将字符串转换为协议将节省我很多工作。
基本上,取一个字符串“GetShapes”,使用MagicMethod()使其吐出来
获取形状.self
满足
的参数
JSONDecoder().decode(type: Decodable.Protocol, from: Data)
func magicMethod(_ string: String) -> Decodable.Protocol {
}