Swift Defer Statement

Swift 2.0 included a number of new language statements. I recently wrote about the Swift Guard Statement. Defer is another statement new to Swift 2.0. Honestly, I don’t use defer as much as guard, but it can be extremely useful.

What defer does is not obvious at first. Defer will wait to execute a block of code until the current scope (loop, method, etc) is exiting. And it will execute that code whether the scope is exiting cleanly, from a guard, or while an error is being thrown.

Here’s the most basic of examples. The defer block exists before the main body of the code, but it’s not called until afterwards.

func simpleDefer() {
	defer {
		print("Leaving.")
	}
		
	print("Main body of the function.")
}
Simple Defer Statement

This can be useful if, for example, there are resources you need to ensure are cleaned up before leaving the current scope.

You don’t need to limit yourself to a single defer statement. You can use multiple defer statements. When more than one are included, they will be called in reverse order. Think of them being included on a stack and popping them off one at a time.

Here’s a simple example of multiple defer blocks. You can see that the order they are defined and the order they are called is reversed.

func multipleDefer() {
	defer {
		print("one")
	}
	
	defer {
		print("two")
	}
}
Multiple Defer Statements

As I’ve stated above, the defer statement isn’t just limited to exiting from methods. You can include them in loops. Look at this example. Everytime the loop is executed, the defer block is called at the end of each loop.

func simpleLoopDefer() {
	var multiplier: Int = 1
	for i in 0..<5 {
		defer {
			print("loop count: \(i); multiplier: \(multiplier)")
		}
		
		multiplier += multiplier * i
	}
}
Simple Loop Defer Statement

If you’re coming from the world of Objective-C or Java, you can approximate the defer statement with a finally block from a throw statement. The syntax is a little different and in Objective-C and Java, you aren’t allowed to have multiple finally blocks. Here’s a Swift example of a defer block being used like a finally block.

func throwsDefer() {
	defer {
		print("clean up from error and non-error states")
	}
	
	do {
		try methodThatCanThrowError()
	}
	catch {
		print("Why??? What did I do??")
	}
}
Try Catch Defer Statement

There is a caveat to using the defer statement. In a defer code block, you cannot transfer control outside of the current scope. You can’t call “return” out of a function, or “continue” out of a loop.

I believe that defer is one of the lesser used statements in Swift. I don’t think it will be used as often as guard. I could probably utilize defer more than I currently am. But it can be useful, so check it out.

GitHub Repo: rwgrier/swift-defer

Swift Guard Statement

Swift 2.0 added the guard statement to the language. Guard is not new with Swift, it’s been around for a while in other programming languages, such as Haskell and Erlang.

Guard statements are very simple and effective. They ensure the check you are performing is true before continuing on. If the result of that check is false the else statement executes, which usually exits a function.

Here’s a very simple example:

func submitForm() {
	guard (validationResults == .valid) else {
		return
	}
	
	// Build form request and submit.
}
Simple Method With Guard

All this does is check the hasValidData variable to see if it’s true. If not, the function exists. This can easily be done with an if statement, like this:

func submitForm() {
	if (validationResults != .valid) {
		return
	}
	
	// Build form request and submit.
}
Simple Method With If

Here’s a less simple example. I can’t say more complex, because it’s slightly contrived just to give a taste of how this could go. The guard statement does a few things here. It checks the optional (UITextField.text property) for a value, unwraps it and assigns it locally. If that check fails, the validation fails and the method exits gracefully.

func validateFormGuard() {
	guard let username = usernameField.text, let password = passwordField.text else {
		return
	}
	
	guard username.lengthOfBytes(using: String.Encoding.utf8) > 3 else {
		validationResults = .invalidUsername
		return
	}
	
	guard password.lengthOfBytes(using: String.Encoding.utf8) > 3 else {
		validationResults = .invalidPassword
		return
	}
	
	guard usernameExists(username) else {
		validationResults = .usernameExists
		return
	}
	
	validationResults = .valid
}
Validation Method With Multiple Guards

This could also be done with if statements:

func validateFormIfs() {
	if let username = usernameField.text, let password = passwordField.text {
		if username.lengthOfBytes(using: String.Encoding.utf8) > 3 {
			if password.lengthOfBytes(using: String.Encoding.utf8) > 3 {
				if !usernameExists(username) {
					validationResults = .valid
				}
				else {
					validationResults = .usernameExists
				}
			}
			else {
				validationResults = .invalidPassword
			}
		}
		else {
			validationResults = .invalidUsername
		}
	}
}
Validation Method With Multiple Guards

If you are checking a lot of properties and conditionals, the if statements can become more nested and can get into a Pyramid of Doom scenario. The guard statement cleans this up and gives you more readable code.

Guard statements aren’t just for easy function exits. You can use them in loops, where if you don’t meet the conditional, proceed onto the next item in the loop (using continue instead of return).

Guard is an extremely useful mechanism in Swift. It allows you to clean up your code. If you’re writing code in Swift, check them out.

GitHub Repo: rwgrier/swift-guard

Beer Styles

I recently released a new app called Beer Styles: BJCP 2015. It’s an iOS Beer Style Guide for homebrewers and hmebrew beer judges. Some of the features include: searchable database and style favorites.

The first version of the app included the 2015 BJCP Style Guidelines. I hope to include other style guides in the future, even if it’s only the 2008 BJCP Style Guidelines.

The base app is free. The base app will always be free. I have some thoughts about adding in-app purchases for things like printing styles and synchronizing your favorites between devices. But these aren’t in the immediate future.

Originally, I had included iAds in the app, but decided to remove them at the last minute. I just didn’t like it.

The app is written entirely in Swift. It started out as a Swift-only project and stayed that way through the end.

I have plans for some of the iOS 9 features announced at Apple’s WWDC. I hope to incorporate those shortly and have a nice update out in time for the iOS 9 release.

Originally, I had included iAds in the app, but decided to remove them at the last minute. I just didn’t like it.

The app is written entirely in Swift. It started out as a Swift-only project and stayed that way through the end.

I have plans for some of the iOS 9 features announced at Apple’s WWDC. I hope to incorporate those shortly and have a nice update out in time for the iOS 9 release.

Fibonacci Sequence

The Fibonacci sequence is a special sequence of numbers. The first two numbers are 0 and 1. The numbers in the sequence after that build on these first two numbers. The pattern is the next number in the sequence is the sum of the two previous numbers.

The Fibonacci sequence begins like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, etc…

Last summer I was interviewing at multiple companies. One interviewer asked me how I would generate a Fibonacci number at a given index.

For example:

Given 0; return 0.
Given 1; return 1.
Given 2; return 1.
...
Given 6; return 8.
Sample Fibonacci Numbers

I started by writing a method that would solve the problem through brute force using recursion, but it wasn’t really what the interviewer was looking for. I fumbled through the question and didn’t get an offer from that company.

Once the interview was over, I made a few half-hearted attempts to figure this out (which I had on Github), but wasn’t happy with anything. I forgot about this entirely until a few weeks ago, when I decided to figure it out.

I did more research into the Fibonacci Sequence and discovered that you can calculate these numbers using the Golden ratio.

The Golden ratio is defined mathematically as:

    (1 + √5)
φ = -------
       2

Or φ ≅ 1.618034…

It turns out you can use the Golden ratio to calculate numbers in the Fibonacci sequence. This is Binet’s Fibonacci number formula:

         φ^n - (- φ)^-n
F(n) = ----------------
               √5

This is a much cleaner approach to the brute force approach for calculating these numbers. Instead of dealing with recursion, which is tricky, this is a straightforward method to calculating Fibonacci numbers.

Here’s what that looks like in code:

Obj-c code

#define SQRT_5 sqrt(5)
#define PHI ((1 + SQRT_5) / 2)

...

+ (unsigned long long) fibonacciAtIndex: (NSUInteger) index {

    if (index < 2) {
        // Save some cycles.
        return index;
    }

    // x(n) = (Phi^n - (-Phi)^-n) / √5
    long double numerator = powl(PHI, index) - powl((long double) (-1.0 * PHI), -1.0 * index);
    long double fibonacci = numerator / SQRT_5;

    return (unsigned long long) fibonacci;
}
Objective-C Code

Larger numbers?

This method above is accurate until an index of 71, after that the numbers drift enough to be noticeable. I haven’t spent much time figuring out how to handle larger numbers. I could probably try NSDecimalNumber or BIGNUM.

I don’t know if this is the best way to generate Fibonacci numbers for a given index. If/When I look into handling larger numbers may find this to be a terrible approach.

OlderNewer