快速使用其他文件中的函数填充数组

问题描述

我正在学习如何使用Github API获取数据并快速制作一个简单的应用程序。我一直在观看的教程在同一控制器文件中创建一个空数组并获得响应功能。但是,我希望我的视图控制器保持尽可能小,并决定在另一个文件中创建获取数据功能。我的问题是,在获取数据后如何访问另一个文件中的空数组。也许这种解释会让您感到困惑,所以我将代码放在下面。

这是我的视图控制器文件,我想在使用API​​调用获取数据后填充repositories数组。

import UIKit

class RepositoryListVC: UIViewController {

    var tableView = UITableView()
    var repositories: [Repository] = []

    override func viewDidLoad() {
        super.viewDidLoad()
    
        title = "AAAAAA"
    
        configureTableView()
    
        Service.fetchData()
    
    }


    func configureTableView() {
    
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 100
        tableView.register(RepositoryCell.self,forCellReuseIdentifier: Cells.repositoryCell)
        tableView.pin(to: view)
    
    }

}

extension RepositoryListVC: UITableViewDelegate,UITableViewDataSource {

    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {

        return 10
    }

    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: Cells.repositoryCell) as! RepositoryCell
    
        cell.set()
    
        return cell
    }

}

这是用于使用API​​调用获取数据的文件。我想在上面的视图控制器文件中填充有价值的repository。我已经成功获取数据并解析了JSON数据,因此我想将Repository(...)推送到repository数组,但是我不知道如何...

import UIKit
import SwiftyJSON
import Alamofire


struct Service {

    static func fetchData() {

        AF.request(API.gitHubEndpoint).responseJSON { (response) in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
            
                let repositoryItemArr = json["items"].arrayValue
                
                for item in repositoryItemArr {                
                
                    Repository(userImageUrl: item["owner"]["avatar_url"].stringValue,userName: item["owner"]["user_name"].stringValue,repositoryName: item["owner"]["repository_name"].stringValue,starNum: item["owner"]["star_number"].intValue)

                }
            
            case .failure(let error):
                print(error)
            }
        
        }

    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...