Core Data的Historic实体日期排序如何避免强制解包,排序失败保留原序
实现方案
方案1:遇nil直接放弃排序,保留原数组顺序
你可以先对数组所有元素的dates属性做非空校验,只要存在任意元素的dates为nil就直接返回原数组,全部非空再执行排序:
private var sortedHistoric: [Historic] { let aux = Array(medication.dates as? Set<Historic> ?? []) // 校验所有元素的dates都非空,不符合则直接返回原数组 guard aux.allSatisfy({ $0.dates != nil }) else { return aux } // 已提前校验无nil,可安全解包执行排序 return aux.sorted { $0.dates!.timeIntervalSinceNow > $1.dates!.timeIntervalSinceNow } }
如果不想使用任何强制解包,可以在排序比较逻辑里加可选绑定,遇到nil直接返回false不调整元素相对位置:
private var sortedHistoric: [Historic] { let aux = Array(medication.dates as? Set<Historic> ?? []) return aux.sorted { guard let date1 = $0.dates, let date2 = $1.dates else { return false // 任意元素的dates为nil就保持原有顺序 } return date1.timeIntervalSinceNow > date2.timeIntervalSinceNow } }
方案2:允许部分排序,nil值统一排在末尾
如果不需要完全放弃排序,仅需避免崩溃,可以把dates为nil的元素统一排到数组末尾,非空元素正常按规则排序:
private var sortedHistoric: [Historic] { let aux = Array(medication.dates as? Set<Historic> ?? []) return aux.sorted { switch ($0.dates, $1.dates) { case let (d1?, d2?): return d1.timeIntervalSinceNow > d2.timeIntervalSinceNow case (nil, _): return false case (_?, nil): return true } } }
内容的提问来源于stack exchange,提问作者fabiofiorita
相关产品推荐
相关产品推荐

