0

I am confused about structure vs class. I have seen this example According to this example structure-vs-class According to link may be code output is 15,15,15,20

BUT code output is because Structure is not changed but when I have run code on Xcode it returns me 15,15,20,20

class objectmanagement
{
    public var x : Int = 10;

    func display()
    {
        print("\(x)")
    }
}



struct StuctManagement{
    var obj = objectmanagement()
}


let SA = StuctManagement()
SA.obj.x = 15

var SB = StuctManagement()
SB.obj = SA.obj

SA.obj.display()
SB.obj.display()

SB.obj.x = 20


SA.obj.display()
SB.obj.display()

I am confused please help me to understand this output this is same as a class output

  • Classes are by reference and you have said that obj for SB is the same as the obj for SA. A class object still behaves like a class object even if it is a property of a struct. In the linked example the property is a struct (String) in the second part. This question should be closed as a duplicate of the question you linked to. – Joakim Danielson Apr 07 '19 at 12:27

1 Answers1

1

In swift class is reference type. (see here)

When you say:

SB.obj = SA.obj

It means that the object of SA is the exact object in SB. (there is one pointer for SA.obj and SB.obj)

Although

let SB = SA

makes copy of SA and create SB with different reference.

Arash Etemad
  • 1,827
  • 1
  • 13
  • 29
  • yes in an example struct type reference is not changed like this struct S { var data: Int = -1 } var a = S() var b = a // a is copied to b a.data = 42 // Changes a, not b println("\(a.data), \(b.data)") // prints "42, -1" b.data is not changed , nut in my code when you run code on xcode it,s answer is changed – Nishant Chandwani Apr 07 '19 at 16:11
  • Mention that objectmanagement is class not struct! – Arash Etemad Apr 07 '19 at 17:12