mesmerizingr
mesmerizingr

Reputation: 1447

Swift 2.0 'inout' function parameters and computed properties

I'm testing Swift 2.0 beta right now and have found strange behaviour. Here is a sample code:

private func someFunc(inout someString: String) {
    print("Inside \'someFunc()\'")

    print(someString)
    someString = "Some another string"
}

private var someAncillaryInt = 42

print(someAncillaryInt)

private var someString: String {
    get {
        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() and why was it when someFunc() got passed with someString.

One can assume that I don't understand intricacies of inout parameters yet and after being passed as inout parameter computed property stops being, em, "computed", but why then was 'setter' called when we set another value to someString?

Thanks!

UPD: I added answer below.

UPDATE 18/11/2015: Apple has updated their manual with detailed explanation of how inout params work.

Upvotes: 7

Views: 2064

Answers (3)

mesmerizingr
mesmerizingr

Reputation: 1447

@Martin R pointed me out on aforesaid thread and, specifically, comment #16 made by Chris Lattner (Swift's mastermind) which helped me to understand 'inout' behaviour. Thanks man!

Consider this code:

private var someString: String {
    get {
        print("Inside getter")

        return "Some string"
    }
    set {
        print("Inside setter")
    }
}

private func someFunc(inout stringArg: String) {
    let funcName = "`someFunc()\'"

    print("Inside " + funcName)

    let someDontMatter0 = 42, someDontMatter1 = 24

    print(stringArg)

    // sets temporary, not the original one. Hence, no calls to setter
    stringArg = "Some other string"
    stringArg = "No matter what string"

    print("These \(someDontMatter0) and \(someDontMatter1)")

    print("Leaving " + funcName)

    // when callee returns, calls the setter with "No matter what
    // string" as a `newValue'
}

// implicitly creates temporary initialised with `someString' value
// getting from `someString's getter.
someFunc(&someString)

For someone coming from C++ background it may seem that the output should be something like:

Inside `someFunc()'

Inside getter

Some string

Inside setter

These 42 and 24

Leaving `someFunc()'

When in fact the output is the following:

Inside getter

Inside `someFunc()'

Some string

These 42 and 24

Leaving `someFunc()'

Inside setter

Kinda funny, right?

This kind of counterintuitive behaviour for someone with C++ background is a result of more fundamental logic which underpins many facets of Swift. As one may get from Chris's comment the general way Swift compiler deals with inout properties is to create temporary object on a stack to store the original value there (hence, call the getter).

So, when you manipulate your inout parameter you deal with temporary object (with initial value you passed to the function) but not with the original one (for me, personally, it's kinda vague. But OK, one can deal with that). And finally:

When the callee returns, the setter is invoked to copy the value back into place

So, if one changes the code a bit:

private var someString: String {
    get {
        print("Inside getter")

        return "Some string"
    }
    set {
        print("Inside setter")
    }
}

private func someFunc(inout stringArg: String) {
    // before returning calls `someString's setter
}

// calls `someString's getter
someFunc(&someString)

the output will be:

Inside getter

Inside setter

Also, the same goes to stored properties:

private func someFunc() {
    var someString = "Some string" {
        willSet {
            print("Inside \'willSet\' with \'newValue\': \(newValue)")
        }
        didSet {
            print("Inside \'didSet\' with \'oldValue\': \(oldValue)")
        }
    }

    func someOtherFunc(inout stringArg: String) {
        print("Inside `someOtherFunc()\'")
    
        stringArg = "First string"
        stringArg = "Second string"
    
        print("Before leaving the function")
    }

    someOtherFunc(&someString)
}

someFunc()

Output:

Inside `someOtherFunc()'

Before leaving the function

Inside 'willSet' with 'newValue': Second string

Inside 'didSet' with 'oldValue': Some string

From Chris's response:

It also guarantees that the getter/setter of a property passed inout will have its getter and setter called once regardless of what the callee does (this is important if the accessors have side effects or are expensive)

Ok, but what if some method which takes inout parameter in some circumstances doesn't modify it (doesn't call the setter or doesn't modify that temporary variable, you name it)? Also, what if I conceived some important logic behind my computed variable's getter and setter and ran into that specific circumstances (just imagine that I open and close files inside getter/setter)? The getter and setter would be called when they had better not.

I'd really like to see the Chris's response in some form in Apple's final Swift 2.0 Programming Guide.

Upvotes: 0

Martin R
Martin R

Reputation: 539765

Your confusion might be caused by choosing someString both as the name of a global variable, and as the name of a parameter of the someFunc() function.

print(someString) inside someFunc() prints the value of the (local) function parameter, which is completely unrelated (and hides) the global someString variable.

It becomes easier to understand if you rename the function parameter

private func someFunc(inout localString: String) {
    print("Inside \'someFunc()\'")
    print(localString)
    localString = "Some another string"
}

which is semantically identical (and therefore produces the same output).

You can think of

someFunc(&someString)

as the following:

  • The value of someString is retrieved (using the getter method).
  • someFunc() is executed, with the local parameter localString set to the value of someString.
  • On return from someFunc(), someString is set (using the setter method) to the (possibly changed) value of the local parameter localString.

More information can be found in https://devforums.apple.com/thread/230567 from the Apple Developer Forum, for example:

Given the guarantee of a getter and setter, inout follows naturally: when calling a function with an inout argument, logically it calls the getter on the var/subscript and copies the value into a stack temporary which is guaranteed to have physical addressability. The physical address of the temporary is passed to the inout argument of the function ... . The callee does whatever it wants with that memory location (and never knows whether the thing passed in was computed or not). When the callee returns, the setter is invoked to copy the value back into place.

and

It also guarantees that the getter/setter of a property passed inout will have its getter and setter called once regardless of what the callee does (this is important if the accessors have side effects or are expensive).

but it is also stated that the temporary copy is avoided if necessary.

Upvotes: 7

matt
matt

Reputation: 535191

I don't understand why wasn't getter called while printing someString inside someFunc() and why was it when someFunc() got passed with someString.

getter wasn't called while printing someString inside someFunc() because it had already been called. We already have this string as the someString parameter internal to someFunc(); we don't need to get it again.

Your output reads:

Inside 'getter' //<-- that's the getter being called!
Inside 'someFunc()'
Some string
Inside 'setter'

Your code runs:

someFunc(&someString) //<-- that calls the getter!

This has nothing to do, by the way, with inout. You'd see the same thing (as far as the getter is concerned) if this had been a normal parameter.

Upvotes: 1

Related Questions