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 = a[i] * 2
i = 1
arrSize -= 1
}
return arr
}
CodePudding user response:
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 }
}