Arrays 从json数据获取项并添加到数组

Arrays 从json数据获取项并添加到数组,arrays,json,swift,Arrays,Json,Swift,我正在使用FlickrAPI检索基于以下代码的搜索的图像。该函数将图像id发送到端点,并返回一个对象,我对该对象进行解析,以获取所述图像的特定url。我得到了我想要的响应,但我正在尝试获取item.source中的所有图像URL,并将它们添加到数组中。我已尝试返回数组,但编译器抱怨无法执行此操作,因为它是来自void方法的非void返回,尽管我将[String]设置为返回。如何将item.source列表作为数组获取,以便在getURLImages()之外使用?或者,我创建了如下的urlsLis

我正在使用FlickrAPI检索基于以下代码的搜索的图像。该函数将图像id发送到端点,并返回一个对象,我对该对象进行解析,以获取所述图像的特定url。我得到了我想要的响应,但我正在尝试获取
item.source中的所有图像URL,并将它们添加到数组中。我已尝试返回数组,但编译器抱怨无法执行此操作,因为它是来自void方法的
非void返回
,尽管我将
[String]
设置为返回。如何将
item.source
列表作为数组获取,以便在
getURLImages()之外使用?或者,我创建了如下的urlsList,并尝试将
项.source
附加到此项,但此项始终打印为空。对于上下文,我计划创建一个
UICollectionView
来显示所述图像/URL

更新

下面是类A中调用类B中的getURLImages的函数:

 let result = try JSONDecoder().decode(Response.self, from: data)
  
 if (result.stat == "ok"){
     for urls in result.photos!.photo {           
         DispatchQueue.main.async {
             GetImageInfo().getURLImages(photoId: urls.id) { urlsList in
                  print("Received \(urlsList)")
              }
         }
      }
 }
let result = try JSONDecoder().decode(Response.self, from: data)
var urlList = [String]()
for item in result.sizes!.size {
    DispatchQueue.main.async {
        if (item.label == "Square"){
            urlList.append(item.source)
                            
        }
    }
 }
 completion(urlList)
以下是B类的功能:

 let result = try JSONDecoder().decode(Response.self, from: data)
  
 if (result.stat == "ok"){
     for urls in result.photos!.photo {           
         DispatchQueue.main.async {
             GetImageInfo().getURLImages(photoId: urls.id) { urlsList in
                  print("Received \(urlsList)")
              }
         }
      }
 }
let result = try JSONDecoder().decode(Response.self, from: data)
var urlList = [String]()
for item in result.sizes!.size {
    DispatchQueue.main.async {
        if (item.label == "Square"){
            urlList.append(item.source)
                            
        }
    }
 }
 completion(urlList)

如何访问函数范围之外的urlsList属性,以便将其实现到UICollectionView中

您不能直接从闭包返回函数的值。您必须为此使用完成处理程序闭包


例如:

func getURLImages(photoId: String, completion: @escaping ([String]) -> Void) {
    ...
    // Call completion handler when you generate your [String] response
    completion(yourImageURLs)
    ...
}

然后像这样使用它:

let urls = [String]()

getURLImages(photoId: "some id") { [weak self] imageURLs in
    guard let self = self else { return }

    print("Received some \(imageURLs)"
    self.urls = imageURLs
    self.updateCollectionViewOrSomething()
}

func updateCollectionViewOrSomething() {
    self.collectionView.reloadData()
}

在函数内部,我将用什么替换YourImageURL?它们当前是通过json响应循环获得的,在特定的键、值出现的位置。我是否会执行完成(urlsList)?在启动for循环之前,可以在闭包中创建一个本地
[String]
数组,并填充该数组而不是
urlsList
,然后在完成中使用该数组。这样,您就可以轻松地将
getURLImages
移动到其他地方,而不会破坏您的代码。为了将您的函数与外部更加隔离,您可以改进参数列表:
getURLImages(photoId:String,config:AppConfig=AppConfig(),completion:…)
通过这种方式,您可以将
getURLImages
移动到其单独的文件或代码库中的任何其他位置,而无需中断现有代码。顺便说一句,当您完成URL收集时,应该调用完成处理程序,因此,在for循环之外。