Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Basics (retired) Collections Modifying an Array

Why we need to write "atIndex" instead of todo.insert("element", 3) for example ?

I already used other programming language and the function "knows" that the second argument would be the index so why we need to write "atIndex:", whereas we dont write "newElement:" before the first argument. Thanks !

2 Answers

atIndex is the required parameter name for apple's provided function "insert". If you were to attempt to insert a String into an array of Strings at the second position, or 3rd index, using

todo.insert("element", 3)

Then the Int 3 is unresolved and doesn't signify anything. It needs to signify the placement in the array that "element" should be inserted- "3" by itself doesn't do that. Only by using the atIndex keyword does the number 3 represent a 3rd index or second placement in an array.

Yes I got that I need to write it, I was just suggesting that the function could know that the second argument is the index, without writing "atIndex" !

Thanks for the answer btw !

Yeah, I agree... seems like a remainder from Objective-C's syntax.