Tech Tip: Use an Object Property to Swap Collection Variables
PRODUCT: 4D | VERSION: 16 R | PLATFORM: Mac & Win
Published On: June 8, 2018
Collections are great, they can hold different types of elements such as strings, numbers, objects, other collections, pointers, etc.
It may seem like swapping two elements of a collection would be difficult and require the use of checking the type of the collection element to swap and then passing it to one of many different temporary variables to swap out. Something like this...
//Given some collection, swap elements 2 and 3 $myCol:=New collection("Hello";"World";15.5;New Object;$pointer) //Check the element to swap for type, and pass to temporary variable then swap Case of : (Value Type($myCol[2])=2) // is text type C_TEXT($temp) $temp:=$myCol[2] $myCol[2]:=$myCol[3] $myCol[3]:=$temp : (Value Type($myCol[2])=1) // is real (number) type C_REAL($temp) $temp:=$myCol[2] $myCol[2]:=$myCol[3] $myCol[3]:=$temp : (Value Type($myCol[2])=38) // is object type C_OBJECT($temp) $temp:=OB COPY($myCol[2]) $myCol[2]:=$myCol[3] $myCol[3]:=OB COPY($temp) : (Value Type($myCol[2])=23) // is pointer type C_POINTER($temp) $temp:=$myCol[2] $myCol[2]:=$myCol[3] $myCol[3]:=$temp //...etc... End case |
There is a better way! Using a temporary object property, this becomes almost trivially easy because the object property can be a string, number, object, pointer, etc:
//Given some collection, swap elements 2 and 3 $myCol:=New collection("Hello";"World";15.5;New Object;$pointer) // Store the element to swap in an object property, then swap! $temp:=New Object $temp.p1:=$myCol[2] $myCol[2]:=$myCol[3] $myCol[3]:=$temp.p1 |