Pete On Software

RSS Feed

Archive for September, 2015

Swift Extension Methods

I’m doing this code in the latest version of Xcode that is available as of this writing, Xcode 7 Beta 6. It does not work with Xcode 6 at all, because some of the features are only part of Swift 2.
Extension CordExtension methods are a language feature that allows you to add behavior to a class (“extend” that class’ functionality, if you will).

In .Net, extension methods are merely syntactic sugar. I previously talked about them here and here. I go into more detail in the links, but basically extension methods are implemented as new methods that take the “extended object” as a parameter. You might declare one something like this:

Then, when I call “Pete”.StartsWithACapitalLetter() it returns true and “pete”.StartsWithACapitalLetter() returns false.

So, that’s .Net. What about Swift? In Swift, similar functionality can be achieved this way.

As it stands, if I call “Pete”.StartsWithACapitalLetter I get true and “pete”.StartsWithACapitalLetter gives me false. Let’s break it down a little more.

The first thing you do is just use the Swift keyword extension in front of the name of the class you are extending. After that, you literally just “add code” to the class. In this case, I added a property (not a method) called StartsWithACapitalLetter that returns a boolean. Notice that within that method, I can use self just as if I had written this code inside of the original class itself.

That’s really all that there is to it.

Swift – Repeat Keyword

RepeatIn the Swift Programming Language – like all programming languages – we are given a lot of ways to control the flow of the program. Back when Swift was first introduced, I wrote a post to talk about the ways that Swift offered to control program flow.

One of the ways that I covered in that post was the while keyword. Using a while statement will cause the program to evaluate a condition first before it would ever execute the block. Take this code for example:

This results in the output of:

However, if you ran the following code:

There is no output. Since counter is 0 and the while block only executes for positive values, nothing happens.

Let’s see how repeat is different. We’ll try the first example again.

This results in the same output of

But, the second example of

Results in the code running for ever and ever and ever. It only asked if the variable was greater than 0 after the first pass. Since by the time the code had exited the repeat block the value of counter was 1 (and therefore positive), we just kept going (I stopped it when the last few entries looked like this):

You might be saying to yourself, but Pete.. this sounds exactly like a do-while loop vs a while loop. Well, you’d be 100% correct. Even according to the Swift documentation, “The repeat-while loop in Swift is analogous to a do-while loop in other languages”. C’est la vie!