英文:
Create nested REST call with Swift
问题
我已经在Stack Overflow上进行了搜索,虽然我找到了一些答案,但似乎没有一个答案能够解决我正在遇到的问题。
我正在尝试为下面显示的REST调用参数编写代码:
{
"asset": [
"Images",
"BsnName"
],
"cntToken": "840009561449",
"language": "us-en",
"idToken": "myToken"
}
有人可以帮助我理解如何设置它吗?
我曾认为下面的代码会起作用,但我收到了错误消息:
在字典字面量中预期 ':'
let params: NSMutableDictionary? = [
"asset": "asset",
[
"Images": "Images",
"BsnName": "BsnName"
],
"cntToken": "840009561449",
"language": "us-en",
"idToken": "myToken"
];
英文:
I have searched Stack Overflow and while I have found some answers none of them seem to address the issue I am struggling with.
I an trying to code for the REST call parameters shown below:
{
"asset": [
"Images",
"BsnName"
],
"cntToken": "840009561449",
"language": "us-en",
"idToken": "myToken"
}
Can anyone help me understand how to set this up?
I had thought the below would work but I get the error:
> Expected ':' in dictionary literal
let params: NSMutableDictionary? = [
"asset": "asset",
[
"Images": "Images",
"BsnName": "BsnName"
],
"cntToken": "840009561449",
"language": "us-en",
"idToken": "myToken"
];
答案1
得分: 1
在Swift中,很少有理由使用旧的Obj-C类型NSMutableDictionary
- 你可以使用Swift的Dictionary
类型。你可以让编译器为你做类型推断,或者像我下面所做的那样显式地注释它。
在你翻译的JSON中,你多加了一个"asset"而不只是将内部的"Array"用作"asset"键的值。此外,内部的值应该是一个"Array",而不是另一个"Dictionary"。
let params: Dictionary<String, Any> = [
"asset":
["Images", "BsnName"],
"cntToken": "840009561449",
"language": "us-en",
"idToken": "myToken"
]
此外,在Swift中,通常不习惯以分号;
结束语句。
英文:
In Swift, there's rarely a reason to use the old Obj-C type NSMutableDictionary
-- you can use the Swift Dictionary
type instead. You can let the compiler do the type inference for you, or you can annotate it explicitly as I've done below.
In your translation of the JSON, you've added an extra "asset" instead of just using the internal Array
as the value for the "asset" key. Also, the internal value should be an Array
and not another Dictionary
let params: Dictionary<String, Any> = [
"asset":
["Images", "BsnName"],
"cntToken": "840009561449",
"language": "us-en",
"idToken": "myToken"
]
Also, in Swift it's usually not idiomatic to end statements with a ;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论