Reputation: 1582
I am trying to build an orders array in Swift. Sometimes the values that get filled in them are nil
. This leads to an app crash. Ho do I handle this?
In the code below, I loop through orders and add them to the orders
array:
var orders: [order] = []
//loop
orders[i] = order(dispatchNumber: "\
(myOrder.DispatchNumber!)",orderId: "\
(myOrder.OrderId!)", source: myOrder.SourceName! , sourceAddress1: myOrder.SourceAddress! ,
sourceAddress2: myOrder.SourceCity! + ", " + myOrder.SourceState! +
" " + myOrder.SourceZip! , destination: myOrder.DestinationName!,
destinationAddress1:myOrder.DestinationAddress!, destinationAddress2:
myOrder.DestinationCity! + ", " + myOrder.DestinationState! + " " +
myOrder.DestinationZip! , loads: "\(myOrder.LoadCount!)",
loadsDelivered: "\(myOrder.LoadsDelivered!)", tons: "\
(myOrder.TonsCount!)", price: "$" + "\(myOrder.PayRate!)", sourceDistance: myOrder.DistanceToSource!, onewayDistance: myOrder.OrderLegDistance!, pickupStart: myOrder.PickupBy!, earliestDelivery: myOrder.DeliverStart!,latestDelivery: myOrder.DeliverBy!,product: myOrder.ProductName! , loadsRemaining: "\(thisLoadsRemaining)", truckType: myOrder.TruckType!, notes:
myOrder.Notes!, isStarted: myOrder.IsStarted, isOnHold: myOrder.IsOnHold, payRateType: "\(myOrder.PayRateType!)",
isStayOn: myOrder.IsStayOn, customerName: myOrder.CustomerName! )
Sometimes myOrder.OrderLegDistance!
gets a nil
value. How do I handle it?
Upvotes: 0
Views: 2476
Reputation: 555
The safe bet would be to check for nil before unwrapping.
var orderLegDistance = defaultValue
if myOrder.OrderLegDistance != nil {
orderLegDistance = myOrder.OrderLegDistance!
}
You can use the same kind of check to determine that you need to ignore the value of myOrderLegDistance
if your logic demands that.
EDIT Adding some additional unwrapping options here:
if let legDistance = myOrder.OrderLegDistance {
orderLegDistance = legDistance
}
Or, as mentioned in a comment below:
orderLegDistance = myOrder.OrderLegDistance ?? defaultValue
Upvotes: 1
Reputation: 5588
Depends of your business rules :
If the OrderLegDistant
is a mandatory value, you may want to 'forget' this order. In order to do that you can use a guard
statement, to check all the mandatory params.
If theOrderLegDistant
is not mandatory, update your model to have this attribute as Optional, and remove the unwrap (!
) from your constructor.
Upvotes: 1
Reputation: 58019
It's generally a bad idea to use implicitly unwrapping. Always handle the values safely.
Use guard let
or if let
to make sure the variables have a value when you work with them.
if let distance = orderLegDistance {
print("\(distance)")
}
guard let distance = orderLegDistance else {
print("Error: distance is empty")
return
}
Moreover, you can define a default value by using ??
.
print("\(orderLegDistance ?? 0)") /*this will print 0 if orderLegDistance is empty*/
On a side note, always use camelCase variable names instead of PascalCase.
Upvotes: 3