How to check if array is null or empty?

前端 未结 12 1387
后悔当初
后悔当初 2021-01-31 07:32

I want to check if my array is empty or null, and on base of which I want to create a condition for example.

if(array ==  EMPTY){
//do something
}
相关标签:
12条回答
  • 2021-01-31 07:47

    Swift 3

    As in latest version of swift 3 the ability to compare optionals with > and < is not avaliable

    It is still possible to compare optionals with ==, so the best way to check if an optional array contains values is:

    if array?.isEmpty == false {
        print("There are objects!")
    }
    

    as per array count

    if array?.count ?? 0 > 0 {
        print("There are objects!")
    }
    

    There are other ways also and can be checked here link to the answer

    0 讨论(0)
  • 2021-01-31 07:48

    As nil maps to 0, which equals NO, the most elegant way should be

    if (![array count])
    

    the '==' operator is not necessary.

    0 讨论(0)
  • 2021-01-31 07:50

    Just to be really verbose :)

    if (array == nil || array.count == 0)
    
    0 讨论(0)
  • 2021-01-31 07:51

    Best performance.

    if (array.firstObject == nil)
    {
        // The array is empty
    }
    

    The way to go with big arrays.

    0 讨论(0)
  • 2021-01-31 07:53
    if (array == (id)[NSNull null] || [array count] == 0) {
        NSLog(@"array is empty");
    }
    
    0 讨论(0)
  • 2021-01-31 07:58
    if (!array || !array.count){
      ...
    }
    

    That checks if array is not nil, and if not - check if it is not empty.

    0 讨论(0)
提交回复
热议问题