开发者

Return double value of each element in array

开发者 https://www.devze.com 2022-12-07 22:20 出处:网络
My function needs to return a new array with each value doubled. For example: [1, 2, 3] --> [2, 4, 6]

My function needs to return a new array with each value doubled.

For example:

[1, 2, 3] --> [2, 4, 6]

I wrote this code, but it's not good:

func maps(a : Array<Int>) -> Array<Int> {
    var arrSize = a.count
    var arr = Array<Int>()
    var i = 0
    while arrSize > 0{
      arr +开发者_JAVA百科= a[i] * 2
      i += 1
      arrSize -= 1
    }
  return arr
}


Note that "it's not good" is extremely unhelpful. You need to explain what is wrong with your code and how it fails to meet your needs. For more complex questions, it's going to be hard for your readers to know what is wrong with the code unless you tell us.

Taking pity on you because you're new:

This line:

arr += a[i] * 2

is not legal. You can't use the += operator to append an item to an array. Replace it with:

arr.append( a[i] * 2)

And your code will work.

Not that you can do this with a single line:

func doubleArray(_ array: [Int]) -> [Int] {
   return array.map { $0 * 2 }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消