简体   繁体   English

动态结构变量名

[英]Dynamic Struct Variable Name

I define a struct as follows:我定义了一个结构如下:

struct MyModel : Decodable {
   var id : Int
   var amount: Int
   let myNewTableId : Int
   let userId : Int 
   let myNewTable : MyNewTable
}

I then use this struct to convert JSON data into an object using JSONDecoder().decode .然后,我使用此结构将 JSON 数据转换为使用JSONDecoder().decode的对象。

The problem is that the myNewTable part of myNewTableId and myNewTable are based on an alias given to the SQL table they originate from.问题是myNewTableIdmyNewTablemyNewTable部分基于赋予它们源自的 SQL 表的别名。 So if the alias is abc the fields should be abcId and abc and if its def it should be defId and def .因此,如果别名是abc则字段应该是abcIdabc ,如果它的def应该是defIddef I've saved this alias into a variable:我已将此别名保存到一个变量中:

let MY_NEW_TABLE_ALIAS = "myNewT"

Is there a way to construct the variable names in the struct dynamically using MY_NEW_TABLE_ALIAS .有没有办法使用MY_NEW_TABLE_ALIAS动态构造结构中的变量名称。 Ideally, when the alias changes on the SQL side, I just want to update one variable, instead of having to update every single struct which uses that table.理想情况下,当 SQL 端的别名更改时,我只想更新一个变量,而不必更新每个使用该表的结构。

简单的方法是首先将 json 转换为字符串,并用所需的键替换出现次数/使用 CodingKeys 并按原样制作结构,顺便说一句,您不能拥有动态变量名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM