You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Swift结构体转换为键名自定义的Dictionary?

How to Convert Swift Struct AddItemToEvent to a Custom Key Dictionary

Got it, let's break this down. You need to map your struct's properties to a dictionary with custom snake_case keys instead of using the struct's camelCase property names directly. Here's a clean, type-safe way to implement this:

First, let's adjust the struct (I added the missing clientId property since it's required in your target dictionary, and added an enum for sourceType to enforce valid values—this is optional but highly recommended to avoid invalid strings):

// Enum to restrict sourceType to only allowed values (optional but safer)
enum SourceType: String {
    case offer, promotion, normal, favourite
}

struct AddItemToEvent {
    var key: String // Note: This property isn't in your target keys, so we'll omit it from the dictionary
    var shoppingListId: String
    var shoppingListName: String
    var commonName: String
    var storeCode: String
    var sourceType: SourceType // Replace with String if you prefer not to use enums
    var sourceId: String
    var isDefaultList: String
    var storeLocation: String
    var clientId: String // Added since it's required in your target dictionary
}

Next, add the getDictionaryEquivalent() method directly to the struct. This method will manually map each property to your custom keys:

extension AddItemToEvent {
    func getDictionaryEquivalent() -> [String: Any] {
        return [
            "shopping_list_id": shoppingListId,
            "shopping_list_name": shoppingListName,
            "common_name": commonName,
            "store_code": storeCode,
            "source_type": sourceType.rawValue, // Use just `sourceType` if you kept it as a String
            "source_id": sourceId,
            "default_list": isDefaultList,
            "store_location": storeLocation,
            "client_id": clientId
        ]
    }
}

Key Notes:

  • Missing Property Handling: I added clientId to the struct because it's listed as a required key in your target dictionary but wasn't present in your original struct definition. If this value comes from an external source or has a default, adjust accordingly (e.g., make it optional with a default value).
  • Enum for Source Type: Using an enum ensures sourceType can only be one of your allowed values (offer, promotion, normal, favourite), preventing invalid strings from slipping in. If you'd rather stick with a String type, just replace SourceType with String and use sourceType directly in the dictionary.
  • Ignoring Unused Properties: The struct's key property isn't part of your target dictionary, so it's omitted from the mapping. If you need to include it, just add a key-value pair like "custom_key": key to the dictionary.

Example Usage

// Create an instance of AddItemToEvent
let groceryItem = AddItemToEvent(
    key: "item_001",
    shoppingListId: "weekly_groceries_123",
    shoppingListName: "Weekly Groceries",
    commonName: "Organic Eggs",
    storeCode: "GROCERY_STORE_007",
    sourceType: .promotion,
    sourceId: "promo_456",
    isDefaultList: "true",
    storeLocation: "Main Street",
    clientId: "user_789"
)

// Convert to the custom dictionary
let itemDictionary = groceryItem.getDictionaryEquivalent()
print(itemDictionary)

This will output exactly the format you need:

["shopping_list_id": "weekly_groceries_123", "shopping_list_name": "Weekly Groceries", "common_name": "Organic Eggs", "store_code": "GROCERY_STORE_007", "source_type": "promotion", "source_id": "promo_456", "default_list": "true", "store_location": "Main Street", "client_id": "user_789"]

内容的提问来源于stack exchange,提问作者nikksindia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:57:40