Nils Garland Nils Garland - 1 year ago 54
Swift Question

How do I get all the data from an array and store it in a new variable or constant?

So I am trying to use the data in my array to add it to a variable. The variable name is

newValue
. I have an array called
numbers
and this is what it looks like

let numbers = [2,8,1,16,4,3,9]


I have another var that is sum 'var sum = 0'. And finally another one called counter
var counter = 0


So! Here is all of my code.

let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0

while counter < numbers.count {
var newValue = numbers
sum = sum + newValue
counter++
}


as you can se I'm trying to add the values to my var newValue. How?

I am so sorry that the code looks like that but it just does not work when I try to make a multi line code block. If anybody know then tell me. Other wise you could place the code in a text editor of some sort idk. Thank all of you so much.

Answer Source

You error is because you are adding Int to [Int], i.e. an Int to Array <Int>(You can only add property of same Type), what you need to do is add Int to and element of Array<Int> by accessing the element by counter as Index value.

Using the value of counter as an index value, retrieve each value from the array and add

let numbers = [2,8,1,16,4,3,9]
var sum = 0
var counter = 0

while counter < numbers.count {
    var newValue = numbers
    sum = sum + newValue[counter] // use counter to access element of Array
    counter += 1 // also ++ is deprecated // now use += 1 instead 
}

print(sum) // 43