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

前端 未结 6 590
旧巷少年郎
旧巷少年郎 2021-01-02 00:02

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

le         


        
6条回答
  •  太阳男子
    2021-01-02 00:55

    Here's another approach.

    You can use flatMap which will remove nil objects and unwrap those that are present. Then, the force unwrap will be safe to sort:

    let flagshipStores = stores.flatMap({ return $0.flagship ? $0 : nil }).sort {
        $0.flagship! && !$1.flagship!
    }
    

    This will remove stores with a nil flagship from the array.

提交回复
热议问题