我正在嘗試將一些值附加到陣列中。問題是有些值是 nils,當我嘗試獲取陣列時,它回傳一個錯誤:
這是我的主要代碼:
class ViewVerPedidos: UIViewController{
@IBOutlet weak var tableOrders: UITableView!
var originOrders = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableOrders.dataSource = self
tableOrders.delegate = self
obtOrders()
}
func obtOrders(){
NetworkingProvider.shared.getAllOrders{ (pedidos) in
for pedido in pedidos{
self.originOrders.append(pedido.origen!) // <-This could be nil or not
}
DispatchQueue.main.async{ [weak self] in
self?.tableOrders.reloadData()
}
} failure: { (error) in
print(error.debugDescription)
return
}
}
extension ViewVerPedidos: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lblOriginOrders.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableOrders.dequeueReusableCell(withIdentifier: "tableviewCellOrders", for: indexPath) as? TableViewCellOrders
cell!.lblOriginOrders.text = originOrders[indexPath.row] // Here mark error nil found!
return cell!
}
}
}
錯誤是因為發現一個 nil:
致命錯誤:在隱式解包 Optional 值時意外發現 nil
我試過,那些:
self.originOrders.append(pedido.origen ?? "nothing found")
如果發現零,則添加一些默認值,但這不起作用
關于如何在發現 nil 時向陣列添加一些默認值的一些想法?
謝謝!
uj5u.com熱心網友回復:
在將結果附加到新陣列的代碼中,您可以改用它……
self.originOrders.append(contentsOf: pedidos.compactMap(\.origen))
這會將陣列映射到Origen屬性上并洗掉所有為零的。無需執行for pedido in pedidos….
我認為您的錯誤來自您創建單元格的方式。您確定在表格視圖中注冊了正確型別的單元格嗎?
你需要使用這個api... https://developer.apple.com/documentation/uikit/uitableview/1614888-register
在你的viewDidLoad函式里面。
tableOrders.register(TableViewCellOrders.self, forCellReuseIdentifier: “tableViewOrdersCell”)
uj5u.com熱心網友回復:
一行解決方案:
var x : [String?] = ["lorum","ipsem",nil]
func myFunc(){
let y = x.map{$0 ?? "Default"}
print(y)
}
結果:[“lorum”,“ipsem”,“默認”]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397319.html
上一篇:基于多個屬性過濾js物件陣列
