You need to be very clear on what you get in var a to z.
Where are those UInt coming from ?
Optional are useful if you need to have a value:
- for instance, if each var was to contain exactly 6 items, you could declare the arrays as [UInt32?]
- but in that case, the array itself doesn't need to be optional
In your case, I understand you will have a variable number of items in arrays:
- a will have one,
- b may have 6
- c may have 0.
But all var a, b, c exist.
So, no need to be optional, but just declare initially as empty (hence no init needed):
var a : [UInt32] = []. // or var a = [UInt32]()
With this, your code becomes (tested in playground):
var totalBits = 0
var a: [UInt32] = []
var b: [UInt32] = []
var c: [UInt32] = []
var d: [UInt32] = []
var z: [UInt32] = []
var aToz : [[UInt32]] = [] // You have to type all var names
func computeTotal() -> Int {
var total = 0
for xx in aToz {
total += xx.reduce(0) { $0 + $1.nonzeroBitCount }
}
return total
}
// Somewhere, you will populate the arrays (getting a JSON Request, typing by user, … whatever way ; here I set manually)
func populateVar() {
a = [100]
b = [50, 200]
c = [125, 6, 314]
d = []
z = [4123]
aToz = [a, b, c, d, z] // You have to type all var names
totalBits = computeTotal()
print(totalBits)
}
populateVar()
I get the result in log:
27
As a conclusion
It is better here to have the same type for all, even to hold a single value or no value.
Globally, you should avoid adding optional everywhere