What's an optional chain

Since this came up in another post lets explore

When you have a variable that holds a reference to an object often in Xojo you had to do


   if myVariable <> nil then
      // do something with the object myVariable references
      // because you know its not nil 
   end if

you had to write this style of code every time

In many other languages there is what’s called OPTIONAL CHAINING - at least that’s what its called in JavaScript but many other language have a similar capability (C# calls it the null conditional operator, Swift also calls it optional chaining, and Kotlin calls it “safe call”)

basically it performs the exact same as the coded check in Xojo just without as much typing

In Xojo you might write

    if  GlobalVars.x_MainWindow <>. nil then
        GlobalVars.x_MainWindow.lbl_Address.Text = "Your Address:"
   end if

in Buoy you can write

    GlobalVars.x_MainWindow?.lbl_Address.Text = "Your Address:"

and its the exact same

4 Likes