我想在Swift中構建一個訂單數組。有時填寫的值是nil
。這導致應用程序崩潰。我該如何處理?在Swift中無值處理
在下面的代碼,我遍歷訂單,並把它們添加到orders
陣列:
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!)
有時myOrder.OrderLegDistance!
得到一個nil
值。我如何處理它?
閱讀類似於https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift#24026093 – DavidN
簡單的方法不會崩潰:不要使用'!'操作符。你如何處理它? – Ssswift
謝謝感謝幫助:) – Ackman