I tested in playground in an init, and no crash:
class OrderTest {
struct Order {
var order: Int
}
var nextOrder: Int?
var allItems : [Order] = []
init() {
nextOrder = self.allItems.map{$0.order}.max()
print("nextOrder", nextOrder)
if nextOrder == nil {
nextOrder = 0
}
print("nextOrder after test", nextOrder)
nextOrder! += 1 // <--- Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
}
}
let orderTest = OrderTest()
So problem is somewhere else.
Could you show the class or structure where this init() is ?
One way I could get it crash was by delaying the allocation of next order with a Dispatch:
class OrderTest {
struct Order {
var order: Int
}
var nextOrder: Int?
var allItems : [Order] = []
init() {
nextOrder = self.allItems.map{$0.order}.max()
if nextOrder == nil {
DispatchQueue.main.async(execute: { // <<-- WITH THIS, IT CRASHES
self.nextOrder = 0
})
}
nextOrder! += 1 // <--- Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
}
}
Did you show the exact and complete init() ?