-2

Array is value type hence it copies data.

var arrayOne  = [UIView(), UIView()]
var arrayTwo = arrayOne
arrayOne.first!.alpha = 0.5
arrayTwo.first!.alpha // How this becomes 0.5?

But arrayTwo.first!.alpha prints 0.5 not 1 Please anyone explain why?

bhavesh
  • 109
  • 14

3 Answers3

6

In Swift, Array is a value type - so the results of arrayOne would be copied to arrayTwo. However, UIView is a reference type, so the references are copied. The references still point to the original UIView which is why you are seeing this behaviour.

totiDev
  • 5,189
  • 3
  • 30
  • 30
1

Arrays are value types in Swift, but still, your items are reference types meaning: both arrays hold values of references and those values are same. In your example, you have two memory addresses stored as two different values on the stack but both values are same and both values point to the same object.

Ivan
  • 264
  • 3
  • 14
1

Arrays are one of the most commonly used data types in an app.

Basically, the type of your array collection is the reference and you are assigning the reference of UIView to another array and the reference will be same if you want to change the reference so you have to do the deep copy.

Salman Ghumsani
  • 3,647
  • 2
  • 21
  • 34