I am really fascinated with the use of Swift on the server. To get more experience with it, I wanted to write something else than just a Hello-World app. So I adapted my previous project TicTacToe to calculate countermoves on the server. In the following I'd like to talk about what I had to do to get client and server running.
As I pointed out in the previous article, TTTBoardCondig in the TicTacToe app contained the logic responsible for the counter move. This logic had to be replaced by a network API call. For this purpose, I created a new class TTTBackendClient with a single method for the network call. It receives and returns a serialized board configuration. For simplicity's sake I hardcoded the server address, a Heroku URL. To serialize and deserialize aforementioned board configuration I extended TTTBoardconfig with two methods. I also added an intializer to instantiate the class with a given String like "XOO-X-X-". The final result can be seen here. Let's talk about the server.
I basically had all the components for the server already. Mind both, Client and Server, are written in Swift. So I just reused TTTBoardConfig from the original game and adapted the Sources from my previous Blog entry with a 'config'-method to deal with any incoming GET call. Reusing TTTBoardConfig required me to shim it which basically consisted of the following two changes:
let startIndex = Int(random() % 9)
let startIndex = Int(arc4random() % 9)
Sources for the server can be found here.
Installation on Heroku
Since Swift is not officially supported by Heroku, a custom Buildpack was needed. Luckily, Kyle Fuller already wrote one. It contains swiftenv, a swift compiler management tool that eases handling different Swift compiler versions, and the required Swift Compiler for this exercise. Besides, it is also possible to run the server locally without Heroku. Just install swiftenv and compile the server sources via 'swift build'. For Heroku however, the following commands need to be run in the server project directory:
- git clone https://github.com/fsaar/TicTacToe-Vapor.git
- heroku create
- heroku buildpacks:set https://github.com/kylef/heroku-buildpack-swift.git
- git push heroku master
This will checkout the server, create an app and push it to Heroku. Last but not least, test the server app once the compilation completes with
- curl <server>/config?XXOO-----
This contrived example showed that more and more things become possible with serverside Swift. We still have to deal with the dependency hell of the frameworks we use. But it gets easier. As I said earlier, I only needed to copy TTTBoardConfig into my server project for this experiment. For production code, when serverside Swift becomes production ready, it would make more sense to share common classes via frameworks. All in all, it was great to see a Swift client and a Swift server running together.