Sid Go
Sid Go

Reputation: 2141

Why does Swift Array behave differently from Lists of other languages?

var sections = [[NoteItem]]()
var section = [NoteItem]()
sections.append(section)

someOtherArray.forEach{n in
    section.append(n)
}

debugPrint("\(section.count)") // prints 75 which is the length of someOtherArray
debugPrint("\(sections[0].count)") // prints 0! Why??

The last output is what I can't understand. In C#, Java, and pretty much other languages I've used, that would have the same output with the second (i.e. 75) because the variable section and the first element of sections which is sections[0] are just the same object.

In Swift, it seems not to be the case. In fact, if I do this instead:

var sections = [[NoteItem]]()
var section = [NoteItem]()

someOtherArray.forEach{n in
    section.append(n)
}

sections.append(section) // appending here after populating 'section'
debugPrint("\(section.count)") // prints 75 which is the length of someOtherArray
debugPrint("\(sections[0].count)") // prints 75 as expected!

I would get the expected output.

Can anyone please explain this? Thanks.

Upvotes: 0

Views: 57

Answers (1)

farzadshbfn
farzadshbfn

Reputation: 2748

Array, Dictionary, String and lots of other types are all Value based in Swift.

So “they’re the same object” doesn’t make sense, because when you add it to sections, you’re just copying the section value.

Upvotes: 2

Related Questions