Returning Reference from Swift Function

I have a use case where I want to return reference from Swift Function just like we can do in C++.

This is How we do it in C++:


int & ReturnIntRef () noexcept
{
      static int a  = 4;

      return a;
}

Do we have equivalent of this in Swift ?

You seem to have a major concern with reference values. What is the main issue you have ?

As a general comment, you should avoid trying to replicate exactly C++ patterns into Swift. Some logics (notably about types, memory management…) are pretty different and it may be risky with dangerous side effects. https://stackoverflow.com/questions/752658/is-the-practice-of-returning-a-c-reference-variable-evil

In your example, what is the purpose of noexcept here ?

Are you sure it is correct ?

int & ReturnIntRef ()

It should be

int& ReturnIntRef ()

Similar pattern in Swift would not work, as the var a would be deleted when exiting the function, unless you use an escaping closure, but that may be overkill.

There are several ways to do what you want.

Are you trying to implement a singleton?

Returning Reference from Swift Function
 
 
Q