WIP: Use Swift Arrays like Lua Tables

This is work in progress and there are somethings that Swift cannot do where as Lua excels with them. Since everything in a Lua table is a reference or a pointer, you can recursively add table to refer to subtables. You could also store functions in the tables and invoke them based on the key. In many ways this can lead to errors as it flaunts the typesafe safety net of swift. Have a read of work so far at http://howto.oz-apps.com/2015/04/create-and-work-with-lua-like-tables-in.html

Storing Functions in an Array/Dictionary

While is not straight forward to store functions in an array/dictionary, it is possible. The way that I see it to work is to store functions that take no parameters and return nothing, so in other words () -> () . You can create an array of type ()->() and store the functions in that array.

//
var myArrayOfFn:[()->()] = []

Then you can add functions to this like so

//
myArrayOfFn["run"] = { println("Running") }
myArrayOfFn["pause"] = { println("Paused") }

and calling these can be as simple as

//
if let run = myArrayOfFn["run"] {
  run()
}

The application of this is upto you, it could be used in similar ways as used in Lua. You could create a state machine and set the functions for different states and the state machine would invoke them if the function is set or available.

Views All Time
Views All Time
1166
Views Today
Views Today
1
Posted in Basics, Tip, Tutorial and tagged , , , , , .