Reputation: 1
I'm new to programming, and having a difficult time taking the array below and performing a mathematical expression on each index then printing the result.
var projectOne = [ 1, 3, 5, 0, 6]
for addition in projectOne {
print( projectOne "plus 4 is" \projectOne = projectOne + 4)
}
Upvotes: 0
Views: 526
Reputation:
One way to do this is to use map
and a closure
to transform the array:
var projectOne = [ 1, 3, 5, 0, 6]
projectOne = projectOne.map() {
let newValue = $0 + 4
print("\($0) plus 4 is \(newValue)")
return newValue
}
You can also use a for..in
loop like this:
var projectOne = [ 1, 3, 5, 0, 6]
for (index, value) in projectOne.enumerate() {
projectOne[index] += 4
print("\(value) plus 4 is \(projectOne[index])")
}
Upvotes: 0
Reputation: 236478
You should be using the addition (array element) inside your loop. You should also take a look at Apple docs String interpolation.
print("\(addition) plus 4 is \(addition + 4)")
If you would like to increment all elements in your array you can enumerate it and add 4 to each element as follow:
for (index,element) in projectOne.enumerate() {
projectOne[index] += 4
print("\(element) plus 4 is \(element + 4)")
}
print(projectOne) // "[5, 7, 9, 4, 10]\n"
Upvotes: 1