在Swift

时间:2016-02-25 01:46:09

标签: arrays swift math

我是编程的新手,很难在下面的数组中执行数学表达式,然后打印结果。

var projectOne = [ 1, 3, 5, 0, 6]
for addition in projectOne {
    print( projectOne "plus 4 is" \projectOne = projectOne + 4)
}

2 个答案:

答案 0 :(得分:1)

您应该在循环中使用加法(数组元素)。您还应该查看Apple文档String interpolation

print("\(addition) plus 4 is \(addition + 4)")

如果你想增加数组中的所有元素,你可以枚举它并为每个元素添加4,如下所示:

for (index,element) in projectOne.enumerate() {
    projectOne[index] += 4

    print("\(element) plus 4 is \(element + 4)")
}

print(projectOne)  // "[5, 7, 9, 4, 10]\n"

答案 1 :(得分:0)

执行此操作的一种方法是使用mapclosure转换数组:

var projectOne = [ 1, 3, 5, 0, 6]
projectOne = projectOne.map() {
  let newValue = $0 + 4
  print("\($0) plus 4 is \(newValue)")
  return newValue
}

你也可以像这样使用for..in循环:

var projectOne = [ 1, 3, 5, 0, 6]

for (index, value) in projectOne.enumerate() {
  projectOne[index] += 4
  print("\(value) plus 4 is \(projectOne[index])")
}