I am currently attempting to learn how to code swift via treehouse.com and so far I am enjoying it. I just came to my first "code challenge" as they call it that I somewhat struggled on. As the title suggested, the started with an empty array as such:
var results: [Int] = []
That is fine and dandy. The goal is to then write a for in loop which finds the multiples of 6 for the numbers 1-10 and then to append those values to the array. I eventually did figure it out, but I am not sure that I did it in the ideal way. I'd appreciate any criticism. My code will be included below. Do bear in mind that I am a total beginner to Swift and to coding in general. Thanks in advance for any suggestions/tips.
var results: [Int] = []
for multiplier in 1...10 {
let multiples = (multiplier * 6)
print(multiples)
results.append(multiples)
}
The code executes properly and the array is appended with the values, but again, I am unsure if there is a better way to do this.
For your first question, Is there batter way or best way to append objects in array in for in
loop is already explain by @Alexander, But if check properly he is still at last doing the same way you are doing the difference is only that he has specified the capacity of array, So the way you are appending object in array is look like perfect but for that you need to write to much code.
Now to reduce your code and do what you are currently doing in a Swifty way you can use built in map
function for that.
let result = (1...10).map { $0 * 6 }
print(result) // [6, 12, 18, 24, 30, 36, 42, 48, 54, 60]
First (1...10)
will create CountableClosedRange
after that we are calling map(_:)
closure with it. Now map
will sequentially take each element from this CountableClosedRange
. So $0
will take each argument from CountableClosedRange
. Now we are multiplying that element with 6 and returning the result from the closure and generate the result according to its return value in this case it will create Array
of Int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With