Search code examples
arraysswiftoption-typeis-empty

Check if optional array is empty in Swift


I realize there are a ton of questions on SO with answers about this but for some reason, I can't get any to work. All I want to do is test if an array has at least one member. For some reason, Apple has made this complicated in Swift, unlike Objective-C where you just tested if count>=1. The code crashes when the array is empty.

Here is my code:

let quotearray = myquotations?.quotations

if (quotearray?.isEmpty == false) {

let item = quotearray[ Int(arc4random_uniform( UInt32(quotearray.count))) ] //ERROR HERE

}

However, I get an error:

Value of optional type '[myChatVC.Quotation]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[myChatVC.Quotation]'.

Neither of the fix-it options to chain or force unwrap solve the error. I have also tried:

if array != nil && array!. count > 0  and if let thearray = quotearray 

but neither of those will work either

Thanks for any suggestions.


Solution

  • You could unwrap the optional array and use that like this, also use the new Int.random(in:) syntax for generating random Ints:

    if let unwrappedArray = quotearray,
        !unwrappedArray.isEmpty {
        let item = unwrappedArray[Int.random(in: 0..<unwrappedArray.count)]
    }