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

时间:2019-01-25 10:00:51

标签: swift alamofire

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!)

3 个答案:

答案 0 :(得分:3)

在循环的每次迭代中,您都在创建一个新的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 }

答案 1 :(得分:1)

您可以声明array的变量在函数之外。

var tuy = [String]()

 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 {
                        tuy.append(names)
                   }
                }
          }

答案 2 :(得分:1)

很简单! 从

中删除该字符串数组var tuy = [“”]
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)

并在函数上方声明它。