首页 > 解决方案 > Swift字典通过另一个键的值设置键的值,格式为:“value_of_key1=value_of_key2”

问题描述

我正在使用 Swift 4 上的 Dictionary,它在委托中具有这种格式,然后将其发送到另一个视图控制器:

{
"search_key": "color"
"option_value": "409"
}

我的要求是以如下格式将其发送到服务器:color=409因为它将用作请求 URL 中的参数。我试图让它像下面的代码一样,但它显示为search_key=409

data["search_key"] = itemFilter[indexPath.section].search_key.count > 0 ?  itemFilter[indexPath.section].search_key : strData.search_key;
data["option_value"] = strData.option_value
dataAfterSet["search_key"] = strData.option_value //this line is when I try to set the format and it show `search_key=409`

guard let dataNew = data as? [NSObject : Any] else {return}

delegate.filterTableCellDidSelectItem(item: dataNew, indexPath: indexPath)

那么,我该如何组合它们呢?我可以做到但仍然保留字典类型,因为在委托中我将它传递给字典中的其他人?

标签: swiftdictionary

解决方案


如果您需要在正文中传递它,我认为您需要这个:

[
"search_key": [
 "color" : 405
],
"option_value": "409"
]

如果您尝试在 URL 中传递它:

let valueToPass = "color=\(405)" // replace 405 with your int value 
let YOUR_URL = "https://example.com/api/" // dont forget the backslash
let url = YOUR_URL + valueToPass

推荐阅读