gpt4 book ai didi

ios - 如何映射 json 响应并创建带索引的简单列表

转载 作者:可可西里 更新时间:2023-11-01 01:11:03 25 4
gpt4 key购买 nike

我正在获取成分,准备来自响应的值,并且我希望此文本在屏幕上显示时以分隔符、破折号和指针呈现。我怎样才能做到这一点?

if let ingredients = dict["ingredients"] as? Array<String> {
self._ingredients = ingredients.joined(separator: " \n - ")

这有效,但不适用于数组中的第一个元素。

4 elements
- 0 : "3 glasses of flour"
- 1 : "1 spoon of salt"
- 2 : "spices"
- 3 : "1 glass of hot water"

我希望它在 ViewController 的标签上看起来像这样:

 - 3 glasses of flour
- 1 spoon of salt
- spices
- 1 glass of hot water

为了准备,我想添加适当的数字指针:

if let preparing = dict["preparing"] as? Array<String> {
self._preparing = preparing.joined(separator: "\n")
3 elements
- 0 : "Mix dry ingredients."
- 1 : "Add hot water, oil, sugar to yeast."
- 2 : "When it's ready add this to flour and start combining"

所以它在标签中看起来像这样:

1. Mix dry ingredients
2. Add hot water, oil and sugar to yeast
3. When it's ready add this to flour and start combining

附加信息 Screen它目前的样子(不要介意语言,它是波兰语)。

在这个 Controller 的生命周期中,我做了简单的 updateUI

func updateUI () {
pizzaDesc.text = pizza.description
ingredientsDesc.text = pizza.ingredients
PreparingDesc.text = pizza.preparings
titleLbl.text = pizza.title
}

//MARK: Lifecycle

override func viewDidLoad() {
super.viewDidLoad()

hideTestDataOnLoad()
pizza = PizzaRecipe()
pizza.downloadRecipeDetails {
self.updateUI()
}
}

最佳答案

用这个 dict 测试:

let jsonText = """
{
"ingredients": [
"3 glasses of flour",
"1 spoon of salt",
"spices",
"1 glass of hot water"
],
"preparing": [
"Mix dry ingredients.",
"Add hot water, oil, sugar to yeast.",
"When it's ready add this to flour and start combining"
]
}
"""
let dict = try! JSONSerialization.jsonObject(with: jsonText.data(using:.utf8)!) as! [String: Any]

情况 1:- 可能不是 分隔符

    if let ingredients = dict["ingredients"] as? Array<String> {
self._ingredients = ingredients.map{" - \($0)"}.joined(separator: "\n")
//...
}

情况 2:您可以使用 enumerated() 获取与每个元素配对的元素索引。

    if let preparing = dict["preparing"] as? Array<String> {
self._preparing = preparing.enumerated().map{"\($0+1). \($1)"}.joined(separator: "\n")
//...
}

关于ios - 如何映射 json 响应并创建带索引的简单列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47062527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com