json 如何将数组导入到函数tableViewController中

rlcwz9us  于 2023-01-10  发布在  其他
关注(0)|答案(2)|浏览(112)

我正在Swift项目中的tableViewController中实现一个表视图。我正在从viewDidLoad中调用的json创建两个数组,viewDidLoad函数中的所有内容都工作得很好。以下是我的viewDidLoad函数。
首先,数组和变量如下所示:

var imageList = ["usaflag","gerflag","franceflag","jpflag","gerflag"]
    
    var titleList = ["Croatian kuna","Hungarian forint","Congolese franc","Israeli Shekel","Nigerian naira"]
    
    var descriptionList = ["HRK","HUF","CDF","ILS","NGN"]
    
    

    
    
    var myCurrency:[String] = []
    var myValues:[Double] = []
    
    var aCheckEuro:Double = 0
    
    var resultCurrency:Double = 0
    
    var activeCurrency:Double = 0
    var zeroOriginActiveCurrency:Double = 0
    var oneDestActiveCurrency:Double = 0
    
    
    
    
    var currencySelected:String = ""
    var zeroOriginCurrencySelected:String = ""
    var oneDestCurrencySelected:String = ""

viewDidLoad在这里

override func viewDidLoad() {
        super.viewDidLoad()
        
       
        let url = URL(string: "http://data.fixer.io/api/latest?access_key=....")
       
        
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            
            
            if (error != nil)
            {
                print("ERROR")
            }
            else
            {
               
                if let content = data
                {
                    do
                    {
                        let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        
                        print(myJson)
                        
                        if let rates = myJson["rates"] as? NSDictionary
                        {
                            for (key, value) in rates
                            {
                                self.myCurrency.append((key as! String))
                                self.myValues.append((value as? Double)!)
                            }
                            print(self.myCurrency)
                            print(self.myValues)
                        }
                        
                    }
                    catch
                    {
                    }
                    
                }
                
            }
            
        }
        task.resume()
        }

就像我之前说的,一切都很好。这些都在一个tableViewController中。问题出在这个函数中

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
       
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
        
        // Configure the cell...
        
        cell.cellTitle.text = titleList[indexPath.row]
        cell.cellDescription.text = descriptionList[indexPath.row]
        
        cell.cellImageView.image = UIImage(named : imageList[indexPath.row])
      
        
        cell.currencyCount.text = myCurrency[indexPath.row] // here has fatal erroe
        
        return cell
    }

最后一行

cell.currencyCount.text = myCurrency[indexPath.row]

有致命的错误,我不知道如何解决它。我应该提到currencyCount是一个标签。

ctrmrzij

ctrmrzij1#

您将创建一个如下所示的数组:

var myCurrency:[String] = []

对于第一次TableView加载,数组为空
在那里你要写这样的代码:

if myCurrency.isEmpty == false {

                cell.currencyCount.text = myCurrency[1]
            }
            else
            {
                self.tableView.reloadData()
            }

}
cigdeys3

cigdeys32#

当tableView加载时,由于网络调用的延迟,myCurrency数组中还没有数据时,可能会发生这种情况。它将抛出一个 *out-of-range异常 *。另外,您可能希望在网络调用完成后立即放置tableView.reloadData。返回方法numberOfItems是什么?

更新:您可以做一些事情。

1.低于self.myValues.append((value as? Double)!)放置

tableView.delegate = self 
    tableView.dataSource = self

1.在您的cellForRowAt中添加验证以检查数组是否为空:

if !myCurrency.isEmpty {
     cell.currencyCount.text = myCurrency[indexPath.row]
    }

相关问题