Making SwiftKilo Part 1: SetupApril 29, 2017 -
Some time ago, I read about AntiRez writing a text editor in C. This dude is pretty hardcore in C and does things like maintain Redis, an in-memory database nearly every startup you ever heard of is using or will soon use. It was super cool to flip through and read about the editor. I was especially impressed by his ability to add search and syntax highlighting even. Some time later, Snaptoken wrote a very thorough tutorial explaining how to make the editor step by step instead of browsing through Antirez's final product. At this point I thought it might be interesting to follow along with the tutorial, but to do it in Swift and write about the differences. Maybe the Swift version will take less lines of code? Maybe more?
The differences between the Swift and C versions of this editor start right at the beginning of this tutorial. Setup for Swift projects is quite different, you can read about it on Swift.org. With this, we can skip past writing Makefiles and stuff because we don't care! Another major difference is that Swift programs don't get a main function to execute. There is
main.swift which gets executed a bit like a script. For my own sanity, I made a main function myself and just executed that function right after. This somehow felt useful to me.
For those of you who are iOS or Mac developers, there are a few differences in a project like this you'll need to get your head around:
- You'll probably be writing Swift in an editor that isn't Xcode. To help make up for other-editor's lack of code completion (which helps a ton when you're not sure how C API's were translated for Swift), I kept open a Playground file like this to test thing:
- Since you aren't using a regular Xcode project (turns out the Swift Package Manager has a way to generate an Xcode project you can use, but I couldn't figure out how to make it work since I'm making a CLI app here and not a Swift library), you'll also get to become familiar with using lldb, the debugger we all know and love since back when gdb was the cool thing, directly. This article by Ankit Agarwal was very helpful for getting my bearings. The output of lldb will often get a little squirrely since you'll be messing with how the terminal behaves and you're debugging your CLI app in the same terminal as you're using lldb to fix it. Hilarity will ensue and you'll find all kinds of off-by-one errors.
Yay, now you're setup for super cool potentially-cross-platform Swift projects. Good luck! If you want to see how I did things in this project, you can find it on github