Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nils Garland
18,416 PointsSwift arrays
Hi! I'm Nils, I am trying to complete a code challenge. Now I tried to click help by the challenge but it would not let me. Anyway what I am trying to do is add an Int type to my array. The message states that I need to add to different Ints to the array but in two different ways. This is what my code looks like and I can't figure out what is wrong with it.
var arrayOfInts = [1,2,3,4,5,6,7]
arrayOfInts.append(8) // This works.
arrayOfInts = arrayOfInts + (9) // The error lies here.
2 Answers
David Papandrew
8,386 PointsHi Nils,
You are close to having the right answer. The trick is that you need to add an array to the existing array for the 2nd method to work. So instead of using the parenthesis, use the square brackets.
Specifically:
arrayOfInts = arrayOfInts + [9] // This adds an array containing a single value to arrayOfInts
J.D. Sandifer
18,813 PointsNot sure if the challenge has changed, but it now asks for you to initialize the array with only six numbers. Here's code that works since it's clear you have all the info needed to create it (and to help out anyone else who finds this later):
var arrayOfInts = [1,2,3,4,5,6]
arrayOfInts.append(7)
arrayOfInts = arrayOfInts + [8]
The last line could also look like this and still work: arrayOfInts += [8]. (I tested that, too.)
Nils Garland
18,416 PointsNils Garland
18,416 PointsHi David! Thanks for the help but I am still getting an error for some reason.
Oops! It looks like Task 1 is no longer passing.
J.D. Sandifer
18,813 PointsJ.D. Sandifer
18,813 PointsAnd once you understand that, you can start using
arrayOfInts += [9]as a shorthand for it. (Exact same functionality, just is easier to write.)