Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of nil values in arrary of Int Optionals

Tags:

arrays

swift

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.

like image 440
bck Avatar asked Dec 03 '22 23:12

bck


2 Answers

You could do:

let countNils = array1.filter({ $0 == nil }).count
like image 149
Connor Neville Avatar answered May 22 '23 09:05

Connor Neville


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
like image 33
dfrib Avatar answered May 22 '23 07:05

dfrib