如何将类/结构转换为字典,其键与属性名称的键不同

问题描述 投票:0回答:1

我有一个结构,我想将其转换为具有属性作为键,其值作为值的字典,但键不应是属性名,而是不同的名称,例如shopping_list_idshopping_list_name

struct AddItemToEvent {
  var key: String
  var shoppingListId: String   //shopping_list_id
  var shoppingListName: String   //shopping_list_name
  var commonName: String
  var storeCode: String
  var sourceType: String
  var sourceId: String
  var isDefaultList: String
  var storeLocation: String

//  shopping_list_id, shopping_list_name, common_name, store_code, source_type (offer, promotion, normal, favourite), source_id, default_list, store_location, client_id 
}

我需要一种用于结构getDictionaryEquivalent()的方法,该方法可能会产生类似["shopping_list_name":"", "shopping_list_id": "", ......]的结果>

我有一个结构,我想将其转换为具有属性作为键,其值作为值的字典,但是键不应是属性名称,而是其他名称,例如shopping_list_id OR ...

ios swift value-type
1个回答
1
投票
您可以使用正则表达式将其转换为蛇形,并使用反射(镜像)将其转换为字典。
© www.soinside.com 2019 - 2024. All rights reserved.