Tag Archives: switch

Apple’s Swift language

I’ve been spending a bit of time over the last couple of weeks on learning the Swift language that Apple debuted at WWDC ’14.  So unfortunately, this post really doesn’t have much to do with computer graphics except that this will eventually become my entry point to working with Metal.  I thought I’d post a bit about Swift – in particular, a few things that have caught my eye from the language so far.  I’m not quite all of the way through the Swift iBook yet, so I’m sure I’ll miss a thing or two.

Swift switch cases do not fallthrough by default.

Swift throws away the old tradition of breaking (via the ‘break’ keyword) to prevent fallthrough and instead introduces a ‘fallthrough’ keyword. So instead of falling through by default, you must explicitly tell Swift that you would like your switch case to fallthrough to the next one. This should save a few headaches and make for tidier code for most people and for most usages.

Values in switch cases can be checked for inclusion within a range.

I can’t express how awesome I think this is.  As someone who’s written Java and C/C++ way too much, simply being able to use ranges is great, but being able to create switch cases for them is amazing.  Here’s what an example of what this might look like in Swift:

var numberOfDigits: String
switch count {
	case 0...9:
		numberOfDigits = "one"
	case 10...99:
		numberOfDigits = "two"
	case 100...999:
		numberOfDigits = "three"
	default:
		numberOfDigits = "many"
}
println("\(count) is a \(numberOfDigits) digit number.")

I can easily imagine that being able to use ranges might eliminate a number of if/else conditional statements in my code and replace it with readable, concise, optimized code.

If this is not enough for you to love Swift’s switch-case statements, keep reading.

You can use tuples to test multiple values in the same switch statement.

I’m sure there’s more than a few ways to use this in computer graphics.  For example, let’s say you want to work with a set of 3D vectors that should all be constrained from 0 to 1, inclusive:

let somePoint = (5.0, 5.0, -4.0) //our example vector
switch somePoint {
	case (0.0...1.0, 0.0...1.0, 0.0...1.0):
		//this vector is already good, let's use it
		doSomeProcessing(somePoint)
	default:
		//this vector needs to be converted
		var newTuple = convert0To1Range(somePoint)
		doSomeProcessing(newTuple)
}

Swift also has wildcards (using the _ character), so you could write a case like this one to satisfy only points on the y-z plane at x = 0:

	case (0.0, _, _):

Or you could bind those y and z values to be used within the case:

	case (0.0, let y, let z):
		println("on the y-z plane at 0.0, \(y), \(z)")

Or do a full blown conditional check as a part of the case:

	case (0.0, let y, let z) where y == z:
		//this case only runs if y is equal to z
		println("on the y-z plane at 0.0, \(y), \(z)")

And we’re not done yet…

You can type check within a case.

Swift uses the ‘as’ keyword to perform type conversions by downcasting.

	case 0 as Int:
		println("Integer zero.")
	case 0 as Double:
		println("Double zero.")
	case let someInt as Int where someInt > 0
		println("Positive integer.")

Optional types are pretty neat.

There’s a chance you could already know (or know someone who knows) C#.  From what I understand, Swift’s optional types has quite a bit in common with C#’s “nullable types”.

The general idea is that unless you specify a variable as having an optional type (with a ? modifier), the variable will be treated as though there is guaranteed to be a value stored in that location in memory.  However, an optional type can have a value of nil.  What’s more, there’s nothing preventing structures of optional types, resulting in ‘optional chains’.  For example:

var myInt = dataStructure?.subStructure?.intValue

The variable myInt gets an inferred type of Int?, or an ‘optional Int’. If either dataStructure or subStructure are nil, myInt gets set to nil and nothing else happens.  Nothing breaks, nothing throws exceptions, we just move on in our code. If both are not nil, myInt gets set to intValue. If we use myInt later on in our code, we would reference it with myInt?. If we are eventually certain that myInt has a value, we can forcibly unbox it with myInt!.

Swift will be another entry point for Metal.

When I first looked at the Metal API docs on Apple’s developer site, I was concerned.  Just about everything I came across was written with Objective-C, which is (in my opinion) not the easiest language to read or write.  Add to that a graphics API whose purpose is to work very close to the bare metal of a GPU, and you have a recipe for unreadable complexity.

But then when I was working within XCode 6 Beta 2, I saw that the game template allowed me to write code in Swift and use Metal for graphics.  I wanted to see what this looked like, so I created a project using the template.  But then something unexpected happened, although being a beta, I probably should have expected it: Metal could not be found by XCode.  In fact, the brand-new project could not compile, let alone run, and I hadn’t even typed anything yet.  What’s more, it turns out that XCode’s simulator won’t run Metal projects (yet) – you must have a device running iOS 8 beta to run them at all, and I don’t have a spare device at the moment.  I guess that XCode Beta just isn’t ready to do it all just yet.

In the meantime, I’m going to continue learning Swift, and when XCode is ready for me to write Swift/Metal, I’ll post some tidbits.