我正在使用同一個結構體的實例數組來填充tableview,並且我被顯示在每個單元格中的數組中的最後一項難住。UITableView在每個單元格中顯示數組中的最後一項
class RoutesViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var routesTableView: UITableView!
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return type1UnownedRoutesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell
for Flight in type1UnownedRoutesArray {
routeCell.originLabel.text = "Origin: \(Flight.origin)"
routeCell.destinationLabel.text = "Destination: \(Flight.destination)"
routeCell.priceLabel.text = "Price: $\(Flight.popularity)"
}
return routeCell
}
與結構體的:
struct Flight {
var origin: String
var destination: String
var mileage: Int
var popularity: Int
var isOwned: Bool
}
如果我添加[indexPath.row]
後for Flight in type1UnownedRoutesArray
我得到Type Flight does not conform to protocol Sequence
在此先感謝您的幫助。
爲什麼'如果let'?這將不會編譯,因爲'type1UnownedRoutesArray [indexPath.row]'不返回可選項。如果索引超出範圍,代碼將崩潰,而不是返回'nil'。 – rmaddy
@rmaddy我不測試,謝謝一如既往,我的答案已更新 –
@rmaddy您是否使用警衛來確保您的indexPath.row不超出範圍?你能檢查我的答案嗎? –