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

NAVEED CHOWDHURY
NAVEED CHOWDHURY
1,142 Points

Reading a specific item in an array after modification

Hi, maybe this is a trivial question but I wanted to know as the instructor pointed out that in the video lesson that creating a constant to read a certain item in a array. After modifying that particular item in the array the constant is still reading the unmodified element in the array. Any thoughts ?

Basically you cant assign an array's element to a constant like this;

let firstElement = someArray[0]

You are just copying the "value" of that array's element to a constant by doing this.

3 Answers

NAVEED CHOWDHURY
NAVEED CHOWDHURY
1,142 Points

// Collections and control flow // Array

var todo : [String] = ["Finish collection course","Buy groceries", "Respond to emails"]

// Add new item at the end of the array using append method todo.append("Pick up dry cleaning")

// Concatinating two arrays

[1,2,3] + [4]

todo += ["Order books online"]

// Array sub-scripting , taking out an element from an array

todo[1]

// In the above we have taken the 2nd item from the array todo

//Next we will read a specific item from the array

let secondTask = todo[1] let thirdTask = todo[2]

//Modifying existing values in an array

// Mutating an array

todo[2] = "Clean kitchen" todo[0] = "Watch Tree House content"

print(thirdTask)

// I want to know why is the constant thirdTask giving the output "Respond to emails".

Check out value types and reference types. As I said before, you are just copying that array's element value to a constant, not assigning it to a constant. Thats why thirdTask doesn't change when you change todo[2]'s value.

NAVEED CHOWDHURY
NAVEED CHOWDHURY
1,142 Points

Thanks Halil for your feedback, I will def read about value types and references.