gpt4 book ai didi

swift - 我正在尝试将值附加到字符串数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:00:23 25 4
gpt4 key购买 nike

func getCategoryNames() {
Alamofire.request(categoriesUrl).responseJSON { (response) in
if ((response.result.value) != nil) {
var jsonVar = response.result.value as! [String: Any]
if let results = jsonVar["result"] as? [[String: Any]] {
for result in results {
if let names = result["name"] as? String {
var tuy = [""]
tuy.append(names)

我正在尝试将这些值(名称)放入选项卡(titleNames:tuy)但它只打印数组的最后一个元素网址是

let categoriesUrl = "https://cmsbmnc.agritechie.com/client/categories/"

我需要这样的输出 tuy = ["ABC", "DEF","XYZ"]

let configure = SGPageTitleViewConfigure()
configure.indicatorStyle = .Default
configure.titleAdditionalWidth = 35
self.pageTitleView = SGPageTitleView(frame: CGRect(x: 0, y: pageTitleViewY, width: self.view.frame.size.width, height: 80), delegate: self, titleNames: tuy, configure: configure)
self.view.addSubview(self.pageTitleView!)

最佳答案

在循环的每次迭代中,您都在创建一个新的 tuy 数组。

您必须在循环之前创建一次数组并将其声明为常规空数组

func getCategoryNames() {
Alamofire.request(categoriesUrl).responseJSON { (response) in
if let jsonVar = response.result.value as? [String: Any],
let results = jsonVar["result"] as? [[String: Any]] {
var tuy = [String]()
for result in results {
if let name = result["name"] as? String {
tuy.append(name)

或者更方便的方式

func getCategoryNames() {
Alamofire.request(categoriesUrl).responseJSON { (response) in
if let jsonVar = response.result.value as? [String: Any],
let results = jsonVar["result"] as? [[String: Any]] {
let tuy = results.compactMap { $0["name"] as? String }

关于swift - 我正在尝试将值附加到字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54362926/

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