I'm trying to append some values to an array. The problem is that some values are nils, and when I try to fetch the array it returns an error:
This is my main code:
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!
}
}
}
The error is because found a nil:
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
I have tried, those:
self.originOrders.append(pedido.origen ?? "nothing found")
for add some default value if found a nil, but this don't work
Some ideas about how to add some default value to an array when found a nil?
Thanks!
CodePudding user response:
In the code where you append the results to the new array you could use this instead…
self.originOrders.append(contentsOf: pedidos.compactMap(\.origen))
This will map the array onto the Origen
property and remove any that are nil. No need to do the for pedido in pedidos…
.
I think your error is coming from how you are creating the cell though. Have you definitely registered the correct type of cell in your table view?
You need to use this api… https://developer.apple.com/documentation/uikit/uitableview/1614888-register
Inside your viewDidLoad
function.
tableOrders.register(TableViewCellOrders.self, forCellReuseIdentifier: “tableViewOrdersCell”)
CodePudding user response:
One line solution:
var x : [String?] = ["lorum","ipsem",nil]
func myFunc(){
let y = x.map{$0 ?? "Default"}
print(y)
}
Result: ["lorum", "ipsem", "Default"]