Named Objects vs Objects created "on the fly"

Hi,


In Swift Playgrounds it is shown how to create e.g. an Object as an Instance of a Class like: let gem = Gem() giving the object a name or create an Instance "on the fly" like: world.place(Gem(), atColumn: 2, row: 5). The first Object created with a name can be used by using its name and its properties and methods. But how is the Object used being created "on the fly" when there is not name for that Object?


Hope above stated makes sense?


Best,

Thomas

Assuming "world" a collection of Gems (likely a matrix given the context of your question), and that the "world" provides a "get" method to retrieve the object located at index(column 2, row 5), that is the reference that would be used. It's really no different than the first statement. The "gem" is a (constant) variable that references the object created by the Gem() constructor. The "world.get(atColumn: 5 row: 2), if it exists, returns the same kind of reference to the Gem() object create by "world.place(Gem(), atColumn: 5 row: 2".

Here is a simple case.


I declare "on the fly":

let myArray = ["Me", "You", "Him"]


if I want to know who is at index 2

let whoIs = myArray[2] // == "Him"


I could have written

let me = "Me"

let you = "You"

let him = "Him"

let myArray = [me, you, him]


I still need to call

let whoIs = myArray[2] // == "Him"


even though I can also use him somewhere directly.

First of all, assignment is not giving the object a name.


This line:

let gem =  Gem()

Creates a box with a name `gem` and put a new instace of `Gem` into the box.


If you declared an instance property like this:

var gem = Gem()

Creates a box with a name `gem` (the box is not sealed), and put a new instace of `Gem` into the box.

Later you would assign another new instance to the property somewhere in an instance method:

func aMethod() {
    ...
    gem = Gem()
    ...
}

Then the old instance is gone, and the newly created instance is put in the box.


So, it is important that how you get the content of the box.


In case of instance property, just write the name of the box, and you can use the content of the box. (In some cases, you need to write `self.`)

gem.aMethodForGem()

The method is called on the current content of the box, not on the first instance created as the initial value.


But in the case of your "on the fly", `world` may prepare a box to store the instance and put the passed instance into it.


How you get the content of the box?


If `world` provides an method to get the content for `place`d instances, for example, if it had a method named `gem(atColumn:row:)`, you might use it like:

world.gem(atColumn: 2, row: 5).aMethodForGem()


When there's no such method in `world`, you may need prepare a box to keep the instance yourself:

var keptGem: Gem?


keptGem = Gem()
world.place(keptGem, atColumn: 2, row: 5)


if let theGem = keptGem {
    theGem.aMethodForGem()
}
Named Objects vs Objects created "on the fly"
 
 
Q