1

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.

0

4 Answers 4

3

randomElement already exists, so don't reinvent the wheel:

var pepBoys: [String]? = ["manny", "moe", "jack"]
// ... imagine pepBoys might get set to nil or an empty array here ...
if let randomPepBoy = pepBoys?.randomElement() {
    print(randomPepBoy)
}

The if let will fail safely if pepBoys is nil or empty.

Sign up to request clarification or add additional context in comments.

1 Comment

This code worked as well. Marking it correct as this version is slightly shorter than @Frankenstein's which also worked.
0

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)]
}

2 Comments

Using if let and isEmpty together looks like a good way to test for an optional array having an element
There is always room for improvement. Just like making the bool check shorter as I just did with unwrappedArray.isEmpty == false statement or calling randomElement on array directly.
0

check the first element is exist or not

var arr: [Int]? = [1, 2, 3, 4]
if let el = arr?.first{
  print(el)
}

Comments

0

I would recommend use guard statement

guard let array = optionalArray, !array.isEmpty else { return }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.