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.
You could do:
let countNils = array1.filter({ $0 == nil }).count
nil
valuesfor 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
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
nil
valuesIt 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With