devbot10
devbot10

Reputation: 1253

How do you check an array to see if it contains a nil value?

I have an empty array full of nil, I will be populating the array full of ints and want to see when it no longer contains a nil value.

I need this check to see if there is nil so I can add ints if there is, and if there is no nil values then stop the game.

var smallestArr = [Int?](count: 25, repeatedValue: nil)

if smallestArr.contains(nil){
    //add ints until it doesn't contain anymore nil
}else{
    //end game
}

Upvotes: 1

Views: 6069

Answers (4)

matt
matt

Reputation: 535546

Instead of

if smallestArr.contains(nil) {

put this:

if smallestArr.contains{$0 == nil} {

Swift 4:

if smallestArr.contains(where: {$0 == nil}) {

Another way:

if smallestArr.flatMap{$0}.count == smallestArr.count {

Upvotes: 12

dfrib
dfrib

Reputation: 73196

Another possible solution, using reduce to count # of non-nil entries (and compare to are length):

var smallestArr = [Int?](count: 25, repeatedValue: nil)

// ...

if(smallestArr.reduce(0) {(tot,num) in tot + (num == nil ? 0 : 1) } == smallestArr.count) {
    // end game
} 
else {
    //add ints until it doesn't contain anymore nil
} 

However I just saw matt:s .contents and .flatMap solutions; his answer is the best, I believe.

Upvotes: 0

Karthik
Karthik

Reputation: 99

You could try something like this:

var smallestArr = [Int?](count: 25, repeatedValue: nil)

var updatedArr = smallestArr.map { (val) -> Int in
    if(val == nil){
    //change this value to the int that you want to replace nil with
        return -1;
    }
    else{
        return val!;
    }
}

updatedArr will have the array where all "nil" are replaced with "-1" and all the other values stay the same.

Having given this answer, I rather feel u should initialize your array in the following manner:

var smallestArr = [Int?](count: 25, repeatedValue: -1)

Because of this, you will avoid nil totally and prevent from going into a fatal error state!!

Upvotes: 1

Benjamin Mayo
Benjamin Mayo

Reputation: 6679

The Array type is not a stack. It is not fixed length, so if you are trying to incrementally replace nil with valid Int values, expecting eventually all the nils to be pushed out, you are mistaken. Although this isn't your question, it seems to be implied understanding given your code sample.

[](repeatedValue:count:) is a convenience method that initialises an array with the same value multiple times. It is the same as making an array and a series of append method calls, it does not give the array special functionality, FIFO or otherwise.

Upvotes: 1

Related Questions