创建嵌套的 Swift REST 调用

huangapple go评论74阅读模式
英文:

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&lt;String, Any&gt; = [
    &quot;asset&quot;: 
        [&quot;Images&quot;, &quot;BsnName&quot;],
    &quot;cntToken&quot;: &quot;840009561449&quot;,
    &quot;language&quot;: &quot;us-en&quot;,
    &quot;idToken&quot;: &quot;myToken&quot;
]

Also, in Swift it's usually not idiomatic to end statements with a ;

huangapple
  • 本文由 发表于 2023年7月14日 00:34:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定