Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, when referencing a class property, is it making a copy of the data?

Tags:

swift

So I'm a little confused because of conflicting information, just looking for some clarity regarding memory allocation for Class properties.

So here are my assumptions, please let me know if any of them are wrong:

  • In Swift, except for Classes and Functions, everything is passed by Value.
  • Classes instances (objects) are allocated on the Heap
  • When you pass an object around, you are passing the pointer
  • When you reference a property on an object, the pointer is dereferenced, and the value of the property is retrieved

So here's my confusion, say my class has a String property, and an Int property. Both Swift data types, that get passed by value in any ordinary situation.

If I ask for let test = object.stringProperty, am I going to get a copy of my string value copied into my test variable?

Similarly, if I had a method inside of my class,

func getAllProperties() -> (String, Int) {
  return (self.stringProperty, self.intProperty)
} 

is object.getAllProperties() going to return a copy of the properties in a tuple?

I know it seems like a basic question, but after reading several sources I just ended up more uncertain than when I started

like image 468
A O Avatar asked Jan 28 '23 15:01

A O


1 Answers

Yes and yes. It doesn't matter that the String and the Int were in a class. You asked for the String or the Int (or both), those are value types, you got copies.

It's easy to prove this to yourself, especially with the String. Just change something about it, and then look back at what the class instance is holding: it will be unchanged.

class C {
    var stringProperty : String
    init(string:String) {
        self.stringProperty = string
    }
}
let c = C(string:"hello")
var s = c.stringProperty
s.removeLast()
print(s) // hell
print(c.stringProperty) // hello

If you want to see the class-as-reference in action, make two of the same instance and do something to one of those:

class C {
    var stringProperty : String
    init(string:String) {
        self.stringProperty = string
    }
}
let c = C(string:"hello")
let d = c
c.stringProperty = "goodbye"
print(d.stringProperty) // goodbye
like image 190
matt Avatar answered Jan 30 '23 05:01

matt