Android Code Snippet Switch - Easily switch the values of a variable, array or object

Switch - This function allows you to easily switch the values of a variable, array or object.

B4X:
'SWITCH by Bruno Silva
'B4X Link: https://www.b4x.com/android/forum/threads/switch-easily-switch-the-values-of-a-variable-array-or-object.59090/
'Switches the values of the given variable, array or object.
'Example:
'Dim myVar = "NO" as String
'myVar = Switch(myVar, "NO", "YES")
Sub Switch(var As Object, default As Object, alternative As Object) As Object
    If var = default Then
        Return alternative
    else if var = alternative Then
        Return default
    Else
        Return default
    End If
End Sub


Usage:
B4X:
Sub Globals
    ...
    Dim LightBulb = "OFF" as String
    ...
End Sub

Sub Button1_Click
    Log("The light bulb was " & LightBulb & ",")
    LightBulb = Switch(LightBulb, "OFF", "ON")
    Log("but now is " & LightBulb & ".")
End Sub


Output:
B4X:
'1st Click:
'    The light bulb was OFF,
'    but now is ON.

'2nd Click:
'    The light bulb was ON,
'    but now is OFF.

'3rd Click:
'    The light bulb was OFF,
'    but now is ON.
 
Last edited:

wonder

Expert
Licensed User
Longtime User
Here's a more advanced example using arrays:
B4X:
Sub Process_Globals
    Type ButtonArray(currentValues() As Int, defaultValues() As Int, alternativeValues() As Int)

    Dim SwitchBoard As ButtonArray
    SwitchBoard.defaultValues     = Array As Int(1, 0, 1, 1, 1, 0)
    SwitchBoard.alternativeValues = Array As Int(0, 1, 0, 0, 0, 1)
    SwitchBoard.currentValues     = SwitchBoard.defaultValues
End Sub

Sub Button1_Click
    SwitchBoard.currentValues = Switch(SwitchBoard.currentValues, SwitchBoard.defaultValues, SwitchBoard.alternativeValues)
End Sub

Note that using a custom type is totally optional.
 
Top