bck
bck

Reputation: 51

Count the number of nil values in arrary of Int Optionals

I'm just starting out with Swift and working with optionals. Struggling to count the number of nils in a test array after using generateRandomArrayOfIntsAndNils()

This is the approach I'm going for:

let array1: [Int?]
array1 = generateRandomArrayOfIntsAndNils()\

var total = 0

for i in array1 {
    if(array1[i] == nil){
    total += 1
    }
}

print(total)

Any recommendations or guidance would be greatly appreciated.

Upvotes: 4

Views: 1299

Answers (4)

dfrib
dfrib

Reputation: 73196

Counting number of nil values

Using for case ...

In addition to the functional approaches already mentioned, you could use a for case ... in loop for conditionally incrementing the total counter

let arr = [1, nil, 3, 4, nil, 6] // [Int?] inferred

var numberOfNilValues = 0
for case .none in arr { numberOfNilValues += 1 }
print(numberOfNilValues) // 2

Using for ... where

Or, alternatively, a for loop coupled with a where clause for the conditional incrementation:

let arr = [1, nil, 3, 4, nil, 6]

var numberOfNilValues = 0
for e in arr where e == nil { numberOfNilValues += 1 }
print(numberOfNilValues) // 2

Counting number of non-nil values

It might also be worth explicitly mentioning that we can similarly use the for case ... approach from above to count the number of values that are not nil (namely, that are .some):

let arr = [1, nil, 3, 4, nil, 6]

var numberOfNonNilValues = 0
for case .some in arr { numberOfNonNilValues += 1 }
print(numberOfNonNilValues) // 4

For this case, we may also use the shorthand (wildcard optional pattern) _? form:

var numberOfNonNilValues = 0
for case _? in arr { numberOfNonNilValues += 1 }
print(numberOfNonNilValues) // 4

Upvotes: 4

Code Different
Code Different

Reputation: 93181

More efficient since it doesn't have to create an intermidiary array holding all the nils:

let array1: [Int?] = [1,2,3,nil,nil]
let nilCount = array1.reduce(0) { $0 + ($1 == nil ? 1 : 0) }

print(nilCount) // 2

How it works:

  • reduce starts with an initial value and iterate through each element on the array
  • We start the count at 0
  • If the element is nil, add 1 to the running total ($0 is the running total, $1 is the current element)

Upvotes: 2

muescha
muescha

Reputation: 1539

next solution for the silly solution contest :)

explanation flatMap removes the nil values :

let arr = [1, nil, 3, 4, nil, 6]

print(arr.count - arr.flatMap{$0}.count 
// 2

Upvotes: 0

Connor Neville
Connor Neville

Reputation: 7361

You could do:

let countNils = array1.filter({ $0 == nil }).count

Upvotes: 10

Related Questions