swift2 - Swift 2.0 'inout' function parameters and computed properties -


i'm testing swift 2.0 beta right , have found strange behaviour. here sample code:

private func somefunc(inout somestring: string) {     print("inside \'somefunc()\'")      print(somestring)     somestring = "some string" }  private var someancillaryint = 42  print(someancillaryint)  private var somestring: string {     {         print("inside \'getter\'")          return "some string"     }     set {         print("inside \'setter\'")         someancillaryint = 24     } }  somefunc(&somestring) print(someancillaryint) 

output:

42

inside 'getter'

inside 'somefunc()'

some string

inside 'setter'

24

i don't understand why wasn't getter called while printing somestring inside somefunc() , why when somefunc() got passed somestring.

one can assume don't understand intricacies of inout parameters yet , after being passed inout parameter computed property stops being, em, "computed", why 'setter' called when set value somestring?

thanks!

upd: added answer below.

update 18/11/2015: apple has updated manual detailed explanation of how inout params work.

your confusion might caused choosing somestring both name of global variable, , name of parameter of somefunc() function.

print(somestring) inside somefunc() prints value of (local) function parameter, unrelated (and hides) global somestring variable.

it becomes easier understand if rename function parameter

private func somefunc(inout localstring: string) {     print("inside \'somefunc()\'")     print(localstring)     localstring = "some string" } 

which semantically identical (and therefore produces same output).

you can think of

somefunc(&somestring) 

as following:

  • the value of somestring retrieved (using getter method).
  • somefunc() executed, local parameter localstring set value of somestring.
  • on return somefunc(), somestring set (using setter method) (possibly changed) value of local parameter localstring.

more information can found in https://devforums.apple.com/thread/230567 apple developer forum, example:

given guarantee of getter , setter, inout follows naturally: when calling function inout argument, logically calls getter on var/subscript , copies value stack temporary guaranteed have physical addressability. physical address of temporary passed inout argument of function ... . callee whatever wants memory location (and never knows whether thing passed in computed or not). when callee returns, setter invoked copy value place.

and

it guarantees getter/setter of property passed inout have getter , setter called once regardless of callee (this important if accessors have side effects or expensive).

but stated temporary copy avoided if necessary.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -