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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.