I have in a viewmodel a reactive closure to return and sort data from a network call based on type (shipping or billing).
Observable.combineLatest(input.headerRefresh, type).flatMapLatest({ (header, type) -> Observable<[AddressItemViewModel]> in
var els : Observable<[AddressItemViewModel]>
els = self.request()
.trackActivity(self.loading)
.trackActivity(self.headerLoading)
.trackError(self.error)
return els.map{
$0.map {
print(type)
var item : AddressItemViewModel!
switch(type){
case .shipping:
if($0.address.isShipping){
item = AddressItemViewModel(with: $0.address)
}
case .billing:
if($0.address.isBilling){
item = AddressItemViewModel(with: $0.address)
}
}
return item // error
}
}
}).subscribe(onNext: { (items) in
elements.accept(items)
}).disposed(by: rx.disposeBag)
When subscribed to elements in the view controller, the app crash at return item.
So my question is how to sort items without using nullable objects? Thanks.
The error :
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
switchis based ontype(a parameter to the closure), whereas your if statements are based on theisShippingandisBillingfields of$0.address. Iftypeis.billing, and$0.isBillingis false, then no assignment will be done, anditemwill benil. - Alexandertype, and what does it mean for it to match or not match the value of$0.address.isX? - Alexandervar item : AddressItemViewModel!if you removed the!from the end of it, the compiler would have told you that it was going to crash and why. - Daniel T.