Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass structure by reference?

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.

like image 593
vbezhenar Avatar asked Oct 18 '14 06:10

vbezhenar


People also ask

How do you pass a structure by reference?

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.

Are structures passed by value or 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).

How do you pass a structure?

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.


1 Answers

For me the best variant was using class-holder:

class Ref<T> {
  var value: T

  init(_ value: T) {
    self.value = value
  }
}
like image 161
vbezhenar Avatar answered Oct 15 '22 05:10

vbezhenar