Упростить код сортировки на swift

  1. Как можно упросить данный код на swift? Попытки не создавать переменные price, priceSale приводят к "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"

  2. Если $0 содержит несколько offers, как лучше поступить?

let itemsWithPrice = items.items.sorted(by: {
                    
   let price = $0.offers?.first?.price
   let priceSale = $0.offers?.first?.priceSale

   let price2 = $1.offers?.first?.price
   let priceSale2 = $1.offers?.first?.priceSale
                    
   if(!asc) {
      return (priceSale ?? price) ?? 0 < (priceSale2 ?? price2) ?? 0
   } else {
      return (priceSale ?? price) ?? 0 > (priceSale2 ?? price2) ?? 0
   }
                    
})
func sortByPrice(asc: Bool) {
        
        let items = self.items.map { $0.id }
        
        NetworkDataFetcher.shared.getItems(items: items, fields: ["price", "price_sale"]) { (itemsResponse) in
            
            if let items = itemsResponse {
                
                let itemsWithPrice = items.items.sorted(by: {
                    
                    let price = $0.offers?.first?.price
                    let priceSale = $0.offers?.first?.priceSale

                    let price2 = $1.offers?.first?.price
                    let priceSale2 = $1.offers?.first?.priceSale
                    
                    if(!asc) {
                        return (priceSale ?? price) ?? 0 < (priceSale2 ?? price2) ?? 0
                    } else {
                        return (priceSale ?? price) ?? 0 > (priceSale2 ?? price2) ?? 0
                    }
                    
                })
                
                dataSource.items = itemsWithPrice.map { Item(id: $0.id, offers: nil) }
                
            }
            
        }
        
    }

Ответы (0 шт):