UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Double the value of numbers in array

Forums > 100 Days of SwiftUI

So, i'm doing the practice in the app and there's one question that i just cannot get past:

"Write code that doubles all the numbers in this array: let numbers = [1, 3, 5, 7, 9] <

The hint is to use a for loop, and I've tried a variety of this code:

for number in numbers {
 number * 2
}
for number in numbers {
 let doubled = number * 2
}

No success. What exactly is the app lookimg for? I'd tried replacing the indexes, creating a new array... nada.

3      

You can create an empty array in where you append the doubled values of your numbers array.

var doubledWithLoop = [Int]()
for number in numbers {
    doubledWithLoop.append(number * 2)
}
print(doubledWithLoop)

But the easier and better way is using .map()

let numbers = [1, 3, 5, 7, 9]
let doubledWithMap = numbers.map { $0 * 2 }
print(doubledWithMap)

Output of this both approaches will be

[2, 6, 10, 14, 18]

4      

Creating an empty array and appending the doubled number worked! Thanks!

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.