Check if an array doesn't contain a specific element

Hi! I have a question. How can I check if an array doesn't contain a specific element?
Thanks in advance!

You can combine ! which toggles a bool, and contains

let array = [1, 2, 3]
let specificElement = 5
let doesntContainSpecificElement = !array.contains(specificElement)
print(doesntContainSpecificElement) // prints true


Thanks! I have another question. How can I make sure that when NextQuestion
is equal to a question that has already been asked, NextQuestion becomes equal to a random element from allQuestions that has not yet been asked.
Thanks in advance!

Here's some code:

if Progress < numberOfQuestions {
               // Next question
                var NextQuestion = allQuestions.randomElement()
                if askedQuestions.contains(NextQuestion!) {
                    NextQuestion = allQuestions.randomElement()
                else {
                ConfiqureUI(question: NextQuestion!)
                Progress += 1

You could approach this a different way and start with your allQuestions collection, but then shuffle it and end up with a new collection that you continually pop off the end until it is empty.

For instance:

var questionsToAsk = allQuestions.shuffled()

// ... later on when you need a next question ...

if let nextQuestion = questionsToAsk.popLast() {
    // Show the next question.
else {
    // Tell the user they are done!

Your idea (trying to randomly pick an element that hasn't be used yet by keeping track of what was already picked) is totally doable. But since we already have shuffled() in the standard library, there's no reason you can't just start with a randomly ordered collection of what you want and then empty it one at a time until you're done.

1 Like
Terms of Service

Privacy Policy

Cookie Policy