Pete On Software

RSS Feed

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:

public static class StringExtensions
{
    public static bool StartsWithACapitalLetter(this string input)
    {
        return !string.IsNullOrEmpty(input) && Char.IsUpper(input[0]);
    }
}

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.

extension String {
    var StartsWithACapitalLetter:Bool {
        if (self.isEmpty) { return false }
        let firstCharacter = String(self.characters.first!)
        return firstCharacter == firstCharacter.uppercaseString
    }
}

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. In my next post, I’m going to do a video to show some of the impressive side effects of the way Swift implements extensions vs something like .Net. When it publishes, there will be a link in the comments below.

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:

var counter:Int = 0

while counter < 10 {
    print("counter is at \(counter)")
    counter++
}

This results in the output of:

counter is at 0
counter is at 1
counter is at 2
counter is at 3
counter is at 4
counter is at 5
counter is at 6
counter is at 7
counter is at 8
counter is at 9

However, if you ran the following code:

var counter:Int = 0

while counter > 0 {
    print("counter is at \(counter)")
    counter++
}

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.

var counter:Int = 0

repeat {
    print("counter is at \(counter)")
    counter++
} while counter < 10

This results in the same output of

counter is at 0
counter is at 1
counter is at 2
counter is at 3
counter is at 4
counter is at 5
counter is at 6
counter is at 7
counter is at 8
counter is at 9

But, the second example of

var counter:Int = 0

repeat {
    print("counter is at \(counter)")
    counter++
} while counter > 0

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):

counter is at 10789
counter is at 10790
counter is at 10791
counter is at 10792
counter is at 10793
counter is at 10794
counter is at 10795
counter is at 10796
counter is at 10797
counter is at 10798
counter is at 10799

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!

Podcast Episode 39 – Warren Buffett’s 25 and 5 Rule w/ bonus Amazon Underground Discussion

Warren Buffett, licensed for reuse from https://www.flickr.com/photos/99132385@N06/10037739284Today, I heard about Warren Buffett’s “Two List Strategy”, also known as the “25 and 5 Rule”. I don’t know if the story is apocryphal or real, but I think the lesson is just as valid. When I got to my picks of the week, the first one went the normal way. But then I started talking about Amazon Underground and apparently I hit a hot button with myself. I ended up talking about Amazon Underground for about as long as Warren Buffett’s strategy. We go where the muse goes 😉


Links Mentioned in this Show:
Warren Buffett’s Two List Strategy
David Smith’s Twitter
Do Not Let Your Users See Spinners
Amazon Underground

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed Listen on Stitcher
In addition, my podcast is available on DoubleTwist and the Windows Marketplace.
Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.
Listen here:

Podcast Episode 38 – A Stream of Consciousness Rant: The Development Community

A StreamIt has been a little while since I posted a new episode, so when inspiration struck me while waiting in the car, I didn’t pass up the opportunity to record Episode 38. I used my phone as a voice recorder and shared a kind of stream-of-consciousness rant. Some things had really piled up on me recently, not the least of which was my disgust with much of the development community at large. Major targets of my focus include judgement of new developers, judgement of people by their technology of choice, my dislike of “Why I’m Leaving X” posts, and how being yourself doesn’t mean that you need to be a douche when interacting with others.


Links Mentioned in this Show:
21 Management Things I Learned at Imgur
Asciinema.org

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed Listen on Stitcher
In addition, my podcast is available on DoubleTwist and the Windows Marketplace.
Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.
Listen here:

The Swift 2.0 Defer Keyword

Couldn't think of a suitable image, so here is a kitten on a computer.At WWDC 2015, Apple announced some substantial updates to the Swift Programming Language for version 2.0. Since its announcement, Swift has been undergoing a lot of updates. In fact, version 1.2 of the language had been released in April 2015 and by June we had the first preview of 2.0.

I decided to blog about some of the changes to the language that really caught my attention. The one that I like the most is the “defer” keyword. In .Net (and other languages), we have this concept of try/finally. Sometimes you can include a catch in there, but it isn’t required. The idea is that after the code executes in the try portion, the code in finally is guaranteed to execute. That’s the perfect place to make sure that you’ve disposed of objects or otherwise cleaned up after yourself. Pretty much every tutorial that I’ve ever seen in .Net has something like this:

try 
{ 
  connection = new SqlConnection(connectionString); 
  connection.Open(); 
  // Do Some Stuff
} 
finally 
{ 
  connection.Dispose(); 
} 

Sharp .Netters might point out that coding a “using” statement accomplishes essentially the same thing with anything that implements IDisposable, but I’m just trying to demonstrate a point 😉

There are a few problems with this try/finally style of coding, however. First, what tends to happen is that developers wrap large blocks of code in try blocks. The problem with that is that you don’t know what actually exists by the time you get to the finally. Maybe you’ve returned early from the method, or maybe an exception was thrown. Now, you’ve got to litter your entire finally block with “if this exists, set it to null” or “if this is open, close it” kind of stuff. That’s where “defer” comes in. Let’s take a look at some code that I ran in an Xcode 7 Beta 2 Playground:

class Foo {
    var Bar : String = ""
    var Baz : Int = 0
}

func showOffDefer() {
    var originalFoo: Foo?
    
    defer {
        print ("Bar was \(originalFoo!.Bar)")
        originalFoo = nil
        print ("Now it is \(originalFoo?.Bar)")
    }
    
    originalFoo = Foo()
    originalFoo!.Bar = "Lorem Ipsum"
    originalFoo!.Baz = 7

    print("We are doing other work")
}

showOffDefer()

Remember, the defer block isn’t called until the function is exited. So, what is written to the console is:

We are doing other work
Bar was Lorem Ipsum
Now it is nil

Do you see the power in that? Now, after I declare an object, I can write a deferred block and it is guaranteed to execute when the function exits. That can be any number of early return statements, that can be because of an exception, or it can be because the function just ran out of code and returned automatically (like mine here). These defer blocks are also managed like a stack, so the most recent defer statements are run first. Let’s see that in action:

class Foo {
    var Bar : String = ""
    var Baz : Int = 0
}

func showOffDefer() {
    var originalFoo: Foo?
    
    defer {
        print ("Original Foo's Bar was \(originalFoo!.Bar)")
        originalFoo = nil
        print ("Now it is \(originalFoo?.Bar)")
    }
    
    originalFoo = Foo()
    originalFoo!.Bar = "Lorem Ipsum"
    originalFoo!.Baz = 7

    print("We are doing other work")
    
    var newFoo: Foo?
    
    defer {
        print ("New Foo's Bar was \(newFoo!.Bar)")
        newFoo = nil
        print("Now it is \(newFoo?.Bar)")
    }
    
    newFoo = Foo()
    newFoo!.Bar = "Monkeys"
    newFoo!.Baz = 42
    
    print("We are doing even more work")
}

showOffDefer()

This gives us

We are doing other work
We are doing even more work
New Foo's Bar was Monkeys
Now it is nil
Original Foo's Bar was Lorem Ipsum
Now it is nil

Hopefully, that example helps make some sense of it. So what did we get? First of all, we got our two print statements that we were doing other work and then even more work showing that the entirety of the function executes before any defer blocks are called. But then it executes newFoo’s defer block first, finishing with originalFoo’s block last.

That seems pretty awesome to me. I realize that Swift isn’t starting anything terribly new here. The Go Programming Language already had this exact concept. That doesn’t mean that it isn’t a good idea.

Swift was created from the very beginning to be a “safe” language and I think defer blocks accomplish this in a few ways. First of all, it ensures that code gets executed. Secondly, it makes sure that only appropriate code is executed (it won’t try to cleanup for objects not yet created). Thirdly, it keeps the cleanup right near the declaration, so readability and discoverability is improved. Why is that safe? If code is easy to read and understand, and the places for modification are well-known and well-understood, then the code is going to be higher quality.

I’m excited for what Swift 2.0 is bringing to the table.

« Older Entries