Check if optional array is empty

后端 未结 7 2242
感情败类
感情败类 2020-11-29 18:21

In Objective-C, when I have an array

NSArray *array;

and I want to check if it is not empty, I always do:

if (array.count &         


        
7条回答
  •  一向
    一向 (楼主)
    2020-11-29 18:58

    The elegant built-in solution is Optional's map method. This method is often forgotten, but it does exactly what you need here; it allows you to send a message to the thing wrapped inside an Optional, safely. We end up in this case with a kind of threeway switch: we can say isEmpty to the Optional array, and get true, false, or nil (in case the array is itself nil).

    var array : [Int]?
    array.map {$0.isEmpty} // nil (because `array` is nil)
    array = []
    array.map {$0.isEmpty} // true (wrapped in an Optional)
    array?.append(1)
    array.map {$0.isEmpty} // false (wrapped in an Optional)
    

提交回复
热议问题