微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决快速使用其他文件中的函数填充数组

我正在学习如何使用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 举报,一经查实,本站将立刻删除。