If I have some existing struct, but I want to use "Reference" behavior, how do I achieve that?
I can write some simple class-holder like
class Box<T> {
var value: T
init(_ value: T) {
self.value = value
}
}
I guess there must be ready class in the standard library, but I didn't find it.
I want to store that reference in my class, so inout parameter isn't what I need.
Passing by reference uses a pointer to access the structure arguments. If the function writes to an element of the input structure, it overwrites the input value. Passing by value makes a copy of the input or output structure argument. To reduce memory usage and execution time, use pass by reference.
A struct is a value type, so it's always passed as a value. A value can either be a reference type (object) or a value type (struct).
Passing struct by reference You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed. During pass by reference, the memory addresses of struct variables are passed to the function.
For me the best variant was using class-holder:
class Ref<T> {
var value: T
init(_ value: T) {
self.value = value
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With