Christian Tuskes Christian Tuskes - 3 months ago 15
iOS Question

swift - sort an array of objects by their optional boolean property without force unwrapping

I can sort this array of store objects by their 'flagship' boolean property, but how can I safely unwrap the 'flagship' property first?

let flagshipStores = self.stores.sort {
$0.flagship! && !$1.flagship!
}

Answer
let flagshipStores = self.stores.sort {
    guard let flagship0 = $0.flagship, let flagship1 = $1.flagship else { return false }
    return flagship0 && !flagship1
}