SLN SLN -5 years ago 116
Swift Question

Function has a return, where it return to? Who is holding it? How long it lives?

I'm always curious what's going on with the return value from a function if I simply call the function without passing it into variables. Where is it returned to? Who is holding it? How long will it hold?

The example below is written by Swift

func returnFun(input: String) -> String {

returnFun("Who Am I?")

is the name of the function and it returns any strings you put into the argument as the string itself. the string Who Am I? had been put into the argument, where does it go? Who catches it? Or it will be destroyed right after returning?

Thanks a lot for your time and help

Answer Source

If you do not store (or otherwise use) a function return value, it will just be discarded.

The process is that the function provides its return value to the caller (usually via CPU registers or the stack), and it is up to the caller to pick it up from there.

Things get a bit more interesting when values are larger than a "machine word" (something that fits in a single register), such as structs or strings (as in your example). Those might require need to passed around as pointers to memory locations elsewhere, and that memory needs to be managed (allocated and released) somehow.

The main conceptual distinction here is between "value types" and "reference types". A Swift string is a value type, which means that it gets copied (at least conceptually, implementation may be different to be more efficient, as long as it results in the same observable behaviour). So you can think of the string being copied from the caller into a local variable input for the function once when you call the function and copied again when it is returned (and not immediately discarded).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download