0

In this excerpt from Big Nerd Ranch Chapter 24, why does takeOwnership() not need to use an inout parameter when it is making a change to asset? Since it is modifying the asset's owner, I would have expected asset to be in-out.

Thank you in advance!

class Person {
var assets = [Asset]()

init(name: String) {
    self.name = name
}

func takeOwnership(of asset: Asset) {
    asset.owner = self
    assets.append(asset)
}

}

  • 1
    Because Asset is a class, a reference type. It is therefore mutable in place and what is passed is a pointer. See https://stackoverflow.com/questions/27364117/is-swift-pass-by-value-or-pass-by-reference and also http://www.apeth.com/swiftBook/ch04.html#SECreferenceTypes – matt Mar 02 '19 at 02:07

1 Answers1

0

Asset is a class, so it's passed in by reference. Changes made to the asset argument are changes to the object being passed in. If Asset were a struct, it would indeed have to be an inout argument.

Checkout this doc

dktaylor
  • 874
  • 7
  • 12
  • Thank you! So the argument itself is constant, and it is an object pointer. Changes to the object it is pointing to are acceptable, but changes to the pointer itself would not be. Is that correct? (I'm more familiar with Java so using the pointer analogy here). – Jon Lee Mar 02 '19 at 02:09
  • No problem! Yep, I think the pointer analogy works. Mostly the thing to know is that classes are passed around by reference (pointer) and struts are passed around by value – dktaylor Mar 02 '19 at 02:12
  • @JonLee If you have any other questions, I'd be happy to elaborate. Otherwise mark this as the answer if you feel it properly answers the question. Thanks! – dktaylor Mar 02 '19 at 17:44