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

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.