Author: rheinard

Building Swift from Source

All my Swift learning thus far has been using the binaries provided from the Swift.org site.  This is good most of the time and it is what I’ve included in my Vagrant project, Vagrant Swiftbox.

Yesterday I decided to update the binaries to a more recent package. That worked well mostly, but somehow I managed to break my libraries (read, copying compiled files to the wrong location).

This was enough to make me thing, there has got to be a cleaner way to upgrade the next build. But that’s not where I stopped, I was thinking in stead, what if I was to build it from source. Then I could reproduce my steps as a script and can feel free to upgrade to whatever development build is available.

Turns out that its a bit harder than I thought to build from source. You have to make sure all the dependencies are in place and when you finally build, be prepared to wait a long time (especially if it fails and you need to figure out why). Once its compiled though, upgrading is a whole lot easier and quicker.

I decided to take what I’ve learned and put it back into Vagrant Swiftbox. This way saving hours of headaches for others who want to poke around the source and compile it. If however you do want to poke around, take a look at the provisioning script and look for the section that reads, “Building Swift from source“. This will save you a lot of searching around.

Also, take a look at the “# Req’d for building Swift from source” section. This will show you what packages you need to build Swift if you want to do it on your own.

I hope this helps someone.

Get better at Swift by learning Haskell

A few months ago someone was desperately trying to get me to learn Haskell. I really wanted to, but kept putting it off. So yesterday I installed ghc a Haskell compiler and started playing. I should have done this ages ago!

So after that intro, its been a few weeks since my last post. Various things have happened, including me developing the dreaded coder’s pinky (painful wrists). So for a while there I was a bit worried and started teaching my computer how to code with my voice. Its doable, but for now simply replacing IDE shortcuts with voice commands, this is already a huge win… ok, back to Haskell.

As I’ve been learning Swift and going through the language I started seeing a lot of things that did not make sense to me, for one, I learned to code with variables at a young age. Why on earth is all Swift documentation trying to get me to use immutable objects? It did not make sense. Then I started seeing some more code that I didn’t understand… Closures in Swift looked so foreign to me. I’m used to anonymous functions in JavaScript, PHP 5.3+ and lambdas in Ruby, but Closures in Swift really had me totally confused.

Enter Haskell. I started noticing notation in Swift that I’ve seen before in a programming Slack channel. It looked similar to Haskell and I got curious. Turns out that Swift was very much inspired by Haskell and other languages. Thats all I needed to know to finally give Haskell a try.

Paradigm Shift

I started playing with Haskell and my mind was blown. Functional programming is very different to my OOP thinking. Favouring struct over class, everything immutablelist comprehensioninfinite lists… this stuff is crazy. But as you play around with it things slowly start to make sense and you can’t help but wanting to learn more.

Back to Swift

After playing only a little bit with Haskell and looking at Swift code again, things are making a whole lot more sense. I realised that I can write functions in Swift without even using func structures, operator overloading, filter, map, reduce, but also writing my own generic functions (not so comfortable with that yet, but getting there).

Functional programming is not the be all end all (IMHO), but it sure helps a whole lot if you’re wanting a deeper and better understanding of what is possible with Swift (and I’m not talking iOS or OSX dev here, I’m talking about the language itself).

If you’re learning Swift or already quite comfortable with it, do yourself a favour, head over to “Learn You a Haskell”. Its a nice guide to help you learn Haskell (despite the comical name).

Happy coding!

Swift Scripting… things to know.

Over the last few days I’ve worked on using Swift as a scripting language for my workflows. Fortunately for me, my system is on OSX because I am somewhat disgruntled with the Linux support.

I try to keep these post sharp and on point, so I’m going to let you in on a secret. My endeavor to understand the Swift language is ultimately to replace all my custom Ruby scripts that automate things for me on my system with Swift powered apps. But not only that, I am attempting to turn these bundles of automation power into cross-platform scripts. So here is what I’ve learned about scripting with Swift on OSX and on Linux… so far.

On *nix type systems, OSX and Linux, we can use the shebang syntax to turn our Swift files into executable scripts. Here is a really quick demonstration of what I mean:

#!/usr/local/bin/swift

print("I am a command line script.");

That first line is called the shebang and is telling our shell where to find the interpreter of our script. In this case where the Swift REPL is installed on your system.  This is important, because it may be in a different location and you’ll need to adjust accordingly.

Tip

If you’re running on OSX, you can change the shebang to: #!/usr/bin/env swift. This will make sure you always use your environment’s version of Swift (you can always change it if your experimenting with other versions).

If you’re running on Linux, unless you know which file you want to use, you can get your environment’s location by running which swift on the command line and copy that path to the shebang.

To run your script you need to change it’s permission, a quick chmod +x myscript.swift will do the trick. Now you can run your script by typing ./myscript.swift. To take it even one step further, you can drop the .swift extension, perform a sudo cp ./myscript /usr/local/bin and run your script from anywhere on your system.

Ok, so that part is easy, but here is where my cross platform woes enter. The Swift core standard library gives you plenty of functionality to write some awesome scripts already, but, for me to replace my scripts I need the power of the Foundation Framework and a few C libraries. Here’s the good news, Foundation is included in Swift on both OSX and Linux. Here’s the bad news, half of the things I want to use in Foundation is not yet implemented.  To see the status of what you can and can’t use, here is the current status: Implementation Status.

All’s not lost, I can create much of what I want to use using some C standard libraries. However, implementation on OSX is different than implementation on Linux, so I need to be able to conditionally check which platform I am running on and import Darwin for OSX or Glibc for Linux. Fortunately I can do that with the following bit of code (I’m also going to define a couple of constants to make checking easier later in my scripts).

// Get Foundation (for what its worth)
import Foundation

let isLinux: Bool
let isOSX: Bool

#if os(Linux)
  // Get Glibc 
  import Glibc
  isLinux = true
  isOSX = false
#elseif os(OSX)
  // Get Darwin
  import Darwin
  isLinux = false
  isOSX = true
#else
  isLinux = false
  isOSX = false
#endif

Now I can make sure I target the right platform with the right code to make sure that my scripts work. And yes, there are many differences. As an example, using addrinfo on Darwin is different from doing so using Glibc. Silly things, like the order of parameters in initializers, or even type differences in some constants.

Its quite the learning experience targeting both platforms, but I am sure that as Swift continues to grow as a language these things will come more into alignment. For example, the Foundation Framework as it is is not recommended for production environments, and is expected to only be fully implemented in Swift 3.0. In the meantime, this gives a great opportunity to learn the ins and outs (Swift humor) of the language without the help of some libraries.

Hope you’re enjoying the ups and downs of this journey as much as I am.

Swift Grammar: Its a language thing.

Usually when I learn a new language I tend to jump straight into the “Hello World” example and get my hands wet immediately. Because I have already used the first iteration of Swift and more recently in a project I used Swift 2, I’m going to do this deep dive into the language a little bit differently.

Rather than starting with examples, I’m going to start with the language grammar. Traditionally this is not how people are taught a language, but I find that looking at the grammar of a language gives you a much better understanding of how the language works.

I’m going to work from the grammar as it is defined in the language reference. See, “About the Language Reference” under the title “How to Read the Grammar” for an explanation of the syntax.

First things first, the grammar is made up of tokens. A token consists of the following: An identifier, a keyword, punctuation, a literal or an operator. This can seem very confusing if you have never looked at syntax before, so lets break down a simple statement.

var number = 2

This is a valid token in Swift. var is a keyword, number is our identifier, = is an assignment operator and 2 is a numerical decimal literal. We know that this token is valid because the Swift grammar tells us that it is. In this case the grammar is:

statement → declaration ;optional

declaration → variable-declaration

variable-declarationvariable-declaration-head pattern-initializer-list

variable-declaration-head → attributesoptional declaration-modifiersoptional var

pattern-initializer-list → pattern-initializer | pattern-initializer, pattern-initializer-list

pattern-initializer → pattern initializeroptional

pattern → identifier-pattern type-annotationoptional

identifier-pattern → identifier

identifier → identifier-head identifier-charactersoptional

identifier-head → Upper- or lowercase letter A through Z

identifier-characters → identifier-character identifier-charactersoptional

identifier-character → identifier-head

initializer= expression

expression → try-operatoroptional prefix-expression binary-expressionsoptional

prefix-expression → prefix-operatoroptional postfix-expression

postfix-expression → primary-expression

primary-expression → literal-expression

literal-expression → literal

literal → numeric-literal | string-literal | boolean-literal | nil-literal

numeric-literal → optional integer-literal | optional floating-point-literal

integer-literal → decimal-literal

decimal-literal → decimal-digit decimal-literal-charactersoptional

decimal-digit → Digit 0 through 9

That is an amazing amount of steps that Swift need to evaluate to determine whether such a simple variable declaration is valid grammar or not. As I was going through the grammar I chose the shortest possible path and I’m glad I only chose one digit. I did not even touch on the full grammar for each of the tokens.

As you are learning Swift I’d encourage you to take a look at the grammar of even your simplest statements to get a more in depth understanding of the language.

I personally find this fascinating to go through code like this, but I’m sure that this post is not for everyone. Hang in there, we’ll get to code soon, but from time to time I might refer back to the grammar.

Enjoy digging into the grammar of Swift.

Geek aside

The manual uses a simple way to represent the grammar of Swift using Bachus-Naur Form (BNF). Some might argue this because of the use of the → symbol over a more accepted ::= sequence of characters, but in the end, its just a representation of how the syntax for the language is structured. Read up on BNF to get a better understanding of language grammars and as an added bonus in your learning, do some reading on finite-state machines (FSM), which could be used as a more visual way to represent a language grammar.

Beginning Swiftly

So Friday turned out to be quite an exciting day!  PHP 7 released, Lets Encrypt went public beta, but the one I want to focus on, Swift officially became open source. I wasn’t too surprised because even at the first release there were rumours and https://swift.org/ already published its vision (which was obvious reading between the lines).

Nevertheless, this is exciting news and I decided that going all in on this means getting your hands on the latest version, which means if you’re on a OSX installing the latest Xcode beta. I was not about to do that and since Swift is available on linux I decided to build a Swift vagrant file. This means that you can easily launch virtual machines that you can start coding Swift 2.2 right away.

If you’d like a copy grab it over here, vagrant-swiftbox, and then head over to Swift.org – Getting Started.

So for the next while as I dive into Swift outside of its normal Xcode habitat I will be documenting my learning here for myself to remember, but also for you to explore.

Happy learning!