如何在 Swift 中创建嵌套的 [String: Anyobject]?
Posted
技术标签:
【中文标题】如何在 Swift 中创建嵌套的 [String: Anyobject]?【英文标题】:how to create a nested [String: Anyobject] in Swift? 【发布时间】:2018-11-27 14:31:06 【问题描述】:我正在通过以下方式创建嵌套的[String: AnyObject]
:
let info = ["para1": test(String) as AnyObject,
"para2": test(String) as AnyObject]
let paramater = ["para_info": info([String: AnyObject]) as AnyObject,
"product_id": test(String) as AnyObject,
"amount": test(String) as AnyObject]
使用 参数,其中 info 是嵌套的 [String: AnyObject]
,但以以下方式请求它作为 POST 请求被视为带有嵌套字典的数组:
try JSONEncoding.default.encode(urlRequest, withJSONObject: parameters)
那么,我是否正确地创建了嵌套的[String: AnyObject]
?
【问题讨论】:
为什么要AnyObject
?在 Swift 3+ 中,所有值类型,如 String
或 Int
都是 Any
。这避免了丑陋的桥梁演员。
但我将AnyObject
用于所有其他 API,它们运行良好。
【参考方案1】:
由于您明确希望它为 [String:AnyObject]:
var dict: [String:AnyObject] = ["messageCode":"API_200" as AnyObject,
"data": ["activities": [["action":1,
"state":1]],
"messages": [["body":"hi"]]] as AnyObject,
"message": "" as AnyObject]
基本上所有的根值都应该被类型转换为 AnyObject
或者很长的路:
//Activities is as Array of dictionary with Int values
var activities = [[String:Int]]()
activities.append(["action": 1,
"state": 1])
//Messages is an Array of string
var messages = [[String:String]]()
messages.append(["body" : "hi"])
//Data is dictionary containing activities and messages
var data = [String:Any]()
data["activities"] = activities
data["messages"] = messages
//Finally your base dictionary
var dict = [String:AnyObject]()
dict["messageCode"] = "API_200" as AnyObject
dict["data"] = data as AnyObject
dict["message"] = "" as AnyObject
print(dict)
【讨论】:
以上是关于如何在 Swift 中创建嵌套的 [String: Anyobject]?的主要内容,如果未能解决你的问题,请参考以下文章