如何在表视图中返回元组数组



我想在tableView函数中创建并返回元组数组,但我不确定如何创建和返回。我相信一种方法是通过分解元组来实现,但我不确定在这种情况下如何执行。我知道最后一个tableView是不正确的,因为它没有返回(String,String(,这只是我的尝试。

class RideHistoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!

let rideHistory: [(String,String)] = [("Driver: Joe, 12/29/2021", "$26.50"),
("Driver: Sandra, 01/03/2022", "$13.10"),
("Driver: Hank, 01/11/2022", "$16.20"),
("Driver: Michelle, 01/19/2022", "$8.50")]
override func viewDidLoad() {
super.viewDidLoad()

tableView.register(UITableViewCell.self,forCellReuseIdentifier:"TableViewCell")
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Code Here
return self.rideHistory.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Code Here
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath)
cell.textLabel?.text = self.rideHistory[indexPath.row]
return cell
}

您可以通过索引(0,1,2,3(访问该元组值

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Code Here
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath)
cell.textLabel?.text = self.rideHistory[indexPath.row].0
print(self.rideHistory[indexPath.row].0) // Driver: Joe, 12/29/2021
print(self.rideHistory[indexPath.row].1) // $26.50

return cell
}

最新更新