0

我正在使用这段代码,当我打印(jsonResponse [“data”])时,我非常快速轻松地从我的 API 收到返回。

但是在第一个循环中我有一个无限循环。由于我的 API 的返回,我需要执行此循环。

任何人都可以帮助我吗?我正在使用相同的代码来获取课程数据并填充表格视图及其工作......但现在对于这门课它不适用于学校,我的 API 收到相同的结构:

SWIFT代码:

func findSchools(){
    let parameters: Parameters = [:]

    let headers: HTTPHeaders = [
        "ContentType": "application/json"
    ]

    API.consultAPI(headers: headers, type: .get, parameters: parameters, endpoint: "schools", completionSuccess: { (response) in

        if let responseValue: AnyObject = response.result.value as AnyObject? {
            let jsonResponse = JSON(responseValue)
            print(jsonResponse["data"])
            for (_, data) in jsonResponse["data"]{
                print(data)

                if data["id"] != nil && data["name"] != nil{
                    let school = School(id: data["id"].int!, name: data["name"].string!)
                    self.arraySchools.append(school)
                }

            }
        }
        print(self.arraySchools)

    }, completionFailure: {(response) in
        if let responseValue: AnyObject = response.result.value as AnyObject? {
            let jsonResponse = JSON(responseValue)
            print(jsonResponse)
            AlertView.showAlert(view: self, message: "Error")
        }
    })
}

API 返回:

{  
"data":{  

 "0":{  
     "id":793,
     "name":"1",
     "default":false
  },

 "1":{  
     "id":3,
     "name":"2",
     "default":false
  },

  "2":{  
     "id":792,
     "name":"28",
     "default":false
  },
  "3":{  
     "id":5,
     "name":"3",
     "default":false
  },
  "4":{  
     "id":9,
     "name":"6",
     "default":false
  },
  "5":{  
     "id":795,
     "name":"793",
     "default":false
  },
  "6":{  
     "id":11,
     "name":"8",
     "default":false
  },
  "7":{  
     "id":4,
     "name":"aasdasdasd",
     "default":false
  },
  "8":{  
     "id":23,
     "name":"Abbotsleigh",
     "default":true
  },
  "9":{  
     "id":24,
     "name":"Academies Australiasia",
     "default":true
  },
  "10":{  
     "id":785,
     "name":"Acme labs",
     "default":false
  },
  "11":{  
     "id":25,
     "name":"Airds High School",
     "default":true
  },
  "12":{  
     "id":26,
     "name":"Al  Amanah College",
     "default":true
  },
  "13":{  
     "id":27,
     "name":"Albion Park High School",
     "default":true
  }
},

"links":[  

]
}
4

1 回答 1

0

在代码中添加 .dictionaryValue ,现在它正在工作(没有无限循环):

 for (_, data) in jsonResponse["data"].dictionaryValue{
    if data["id"] != nil && data["name"] != nil{
      let school = School(id: data["id"].int!, name: data["name"].string!)
           self.arraySchools.append(school)
    }
 }
于 2017-07-20T01:22:11.107 回答