Guards in Swift

During the announcement of Swift 2.0 at WWDC 2015 I was very excited to see what new features they had put in the language. So when the Swift 2.0 features where presented on one of the slides I saw a lot of cool things that piqued my interest. At first I was wondering what a guard was because we already have guards in Swift in the form of the pattern matching in the switch statement with the 'where' keyword (at least if you compare how guard and where works in Haskell). After reading what guards in Swift was I understod how to use them but I felt like they didn't really add anything to the language. But after adopting 'guard's in my own projects I think this features have aided Swift in the most important feature a language can have, tools to write clear and readable code.

I will try to show you the power of 'guard' and give my opinion, when and why you should use it. As I am one of the most original people on the internet I've decide to demonstrate 'guard's with an addition function. But not an ordinary addition function because this functions will return a nil optional if the first argument is not even. To make my example code clearer and easier to read I have extended the IntegerType protocol with a computed property that checks if the integer is even or not.

In the first attempt to implement this function one would probably do some thing like the code below in Swift pre 2.0. This implementation works as intended but could in my opinion be clearer. First it checks if 'x' and 'y' are not 'nil' and if 'x' is even. If all of this is true then return the result otherwise return '.None' (which is equivalent to nil).

Instead of using 'if let' one could utilize 'guard's to check if the inputs are valid and if they are not it return '.None'. There are two things that make this approach clearer than the other one. First they don't nested code because guard automatically unwraps optional for the rest of the scope. And secondly the guard keyword is used to guard against bad values and makes what is happenin clear for the reader.

But we can do better, let's have two guard statements to separate the validation of the input. By doing it this way it is very clear what input this implementation accepts. This is not something we could do with 'if let' without having to nest and 'if let' in another 'if let'.

I like to keep the nesting of code to a minimum and 'guard's is a great way to achieve it  (nobody likes a pyramid of doom). The 'guard's help you divide up the implementation details into understandable chunks of code like input validation and logic.

More reading.

Trim the dynamics form the view controller

One of the hardest part of iOS development is to keep the view controller slim and nice. I myself have lots of time been victim of my own ignorance and bloated my view controller to get the application up and running as soon as possible and said to myself that I will separate the model and view code from the controller once the application is working as intended. The longer you postpone this the uglier and unmaintainable the code gets so I have really started to question myself every time I implement something in the view controller, sometimes there is an obvious answer and sometimes there isn't.

The thing I have been wondering about is UIKitDynamics and its best practices. Most of the time when I see UIKitDynamics code it is implemented in the view controller and for most simple cases this will suffice and if you need to add a lot of behaviors to get the result you want you can always subclass UIDynamicBehavior to make a custom one for your specific scenario. But what if you want to make something more complex like change the way a button handles it different states?

By putting it all in the view controller you will quickly find yourself with one nasty view controller. But the convenient thing about putting UIKitDynamics in the view controller is that you can easily create one UIDynamicAnimator and put all your behaviors there, you could in most cases get away with one UIGravityBehavior behavior and one UICollisionBehavior. And not lets not forget the the controller is the intersection of the model and the view so the controller knows the state of both and you can easily let your dynamics react to very specific scenarios.

But in my cases all the logic the button needed was what actions the button was sending. So I decided to subclass UIButton and put all the dynamics in there. I'm quite happy with results, the code is easy to understand and my controller dose not need to worry about any dynamics. I know that some people frown upon subclassing UIButton and argue that subclassing UIControl is the right way to do it, but for some simple cases as long as you don't depend on the button being any specific typ it works fine.

If something dose not seem to belong in the view controller there probably is a better place to put it. If you are interested I have posted the code below, the current state of the code is questionable as it is not very modular and only solves my specific problem, but it dose work quite well with auto layout. I could have gotten away with only one UIDynamicAnimator and UIGravityBehavior if swift supported regular class variables (I know there is a way around this with static struct variable with a calculated property but I don't like that solution). I hope it gives you some inspiration on how you can separate your UIKitDynamics from the view controller.  

Swifter and better

Swift is really growing on me, I didn't think we needed a new language for iOS development but I find it hard to go back to Objective-C now. I think Swift lets us express ourselves with less code and still make it simpler if we dare to think a little different about how we will solve our problems. Ash Furrow mentioned this and I think he has a point, The tools are different so the solution should be too, right?

How do we, as iOS and OS X developers, solve familiar problems with new tools? It would be a shame to ignore this opportunity and just continue to write in Objective-C, but using Swift syntax. / Ash Furrow

So I currently have a game in the app store that is called Solution. Its a game about math so It has a class called expression that holds an mathematical expression that is valid for for the game. One of the most important functions of this class is to not allow any input that is not valid for the expression. The code below is the implementation of this method when the app shipped.

Theres a lot of things going on, I use NSCharachterSet extensively and those nested if statements aren't pretty. The code can be a lot to take in at a first glance but its not very complicated or hard to read its just not very smooth. What I mean is that you have to to look and concentrate to really understand whats happening. Sometimes thats the best you can get with the tools you have and I'm sure this code could be written better than it is but at the time I wrote it this was the best I could do.

Below is my first attempt of writing the same method in Swift. I use pattern matching with some nested switch statements. But is it really any better than the Objective-C code above? You could argue that it is better and safer, but its not much smoother. Well I thought I could do better so I tried again.

So below is my second attempt of writing this method in Swift. A lot smoother wouldn't you say? I really tried to embrace the new things about swift like tuples and pattern matching. As you could see the code is at least shorter, what used to be 47 lines is now 15. Shorter code is not equal to better code, but in this case I think the short swift version is superior in readability and that is how I like my code, readable.


A Swift good bye to Objective-C

The big surprise for WWDC 2014 was Swift, I was a bit shocked when they announced it as I was one of the persons who defended Objective-C when others bashed on it. As much as I liked the C part of Objective-C It did make the language look weird compared to other languages with prefixes like @ in front of some keywords, all the square brackets and let's not get started on that block syntax.

Despite all Objective-C’s faults I was enjoying working with it and reading about all the cool stuff people did with the runtime like method swizzliering. But who are we kidding, Objective-C is an old language with a lot of baggage and the best part of Objective-C is the Cocoa framework. So I was pleased to read that the you could still use the Cocoa framework with Swift so there is no need to relearn the framework. 

I have now been programming and reading about Swift since it came out in june and it is currently on beta 5. Some features have been added and some small syntax changes have been made since beta 1. I have to say that the more I work with language the more I like it, I can can easily say its the most pleasant language I have used to date and that includes both imperativ and functional languages.

The thing that have been taking more of my time that I should have allowed it to is solving Project Euler problems in Swift. I choose to do this for a couple of reasons. I have never gone beyond problem two before, it’s a good way to learn the ins and outs and its fun. One challenge with these problems is to make them easy for the reader to understand whats happening as there is a lot of math going on that can be ambiguous. So I have been striving for both performance, readability and reusable code.

I think I have achieved this with the problems I have solved so far except for problem 10, the current solution is easy to read and understand but the performance is not as great. I have tried to implement Sieve of Eratosthenes in some different ways but my solution with calling the reduce function with a prime number checker function is way faster. And I can’t figure out if my attempts with Sieve of Eratosthenes where bad or if the reduce function is so optimized that its hard to compete with it.

So if you are in to iOS/OS X development or curious about it theres no better time than now, maybe the App Store gold rush of the early days are gone but so are many of the frustations like memory management and unchecked collections. I know that I won't be starting any new projects with Objective-C and I will rewrite my two Application in Swift as soon as I get the time.



Solution: The Game

So i finally released my game last week on the iOS app store. The game works as aspected except for some bugs that I have found(working on an update). The game is in its current state a local competitive math game that can be played with only one iOS device. I'm also working on an update to get online multiplayer working and an arcade mode with leaderboards.

The game is easy to play so I recommend that you try it(of course I recommend it, I made it). If you have any feedback I would love to hear it. 


Software I use on the Mac

For everyone

Every Mac comes with great software out of the box, but for most of us thats not enough. We need more to make the most out of our Mac. Here is a brief list of applications that I use the most and highly recommend that you at least try them if you find them interesting.


For some time people have been talking good about this application for the Mac and iOS. I have looked at it and thought "wow, thats a cool app, but i have no use for it". Well when I showed a friend of mine the app who I thought could really benefit from the application I realized that so could I. As a computer science student I really liked the hex and binary math. But its the combination of math and text that makes it so good.   


This is one of those apps that I use rarely, but when I do use it I'm very glad that I bought it. Its a must for anyone who wants to make beautiful flow charts and diagrams with ease. If you put some time into your omnigraffle documents people will be impressed.


Not much to say, its like MS Word but not as bloated, ugly and boring. Its a great cheaper(free with new Macs) alternative that will probably satisfy all your text document needs.


Same as above, not the most powerful in features as Excel but easier to use, a lot easier.


This is a must if you ever need to make a presentation, there are more experimental and cool projects out there like or that is worth a test or at least a look, but keynote is a classic and for somethings you just can't beat the classic.


If security is important to you (which it should be) really need to take a look at 1Password. It helps you mange all your passwords, sync them and even make it easy to create new ones. But my favorite feature is that it says which passwords are duplicates and which ones are really old and should be updated.


I seldom use it and I'm not very good at image manipulation, but damn this is a good application. its one of those apps that makes you wanna get better skills so you have a excuse to use it more.


For the programmer

As a iOS developer and Computer Science student I have found some applications that are very valuable to me, let me share which and why.


This application blew my mind when it was released. its so good that I often show it to non programmers and explain why its so cool and useful. Its a WYSIWYG graphics editor that generates the drawing in code, do I need to say more? no, I shouldn't need to sat more and you should at least try it if you're into iOS development.


A simple but useful application. Its a text editor that help you compile and run code in many of the popular languages. It makes it easy to test snippets of code without the hassle of a clunky IDE. And that is why its so good, its simple for simple needs.


Ever wanted easy access to documentation? if your answer is yes Dash is the way to go.


I love the Xcode, I read a lot of hate of Xcode on the web but its treats me good so I'm happy. Sure Xamarin is probably a good choice is you want multi platform and AppCode feature list looks promising, but Xcode does all I need it to do and it dose it well, I haven't really tried the alternatives for iOS development so i don't know which is better(but I do know its miles netter than Eclipse).


More to discover

I know I've missed a lot of cool applications, but these are what I use the most on my Mac today. The good thing is that there are many cool application I haven't tried yet that I look foreword to try and hopefully they will make my life easier and more enjoyable. The applications that I keep hearing good things about are Spark inspector, AppCode, xScope, Kaleidoscope and Briefs.



Keep learning the coding

Don't stop

In my post about learning to code I talked a lot about my first experience (that failed) and second experience(which succeeded) in trying to learn to code. I also had some recommendation on where you could start with learning some Objective-C and iOS development. This post is for you who want more and keep up with whats happening in the world of Objective-C and the iOS SDK.

First thing I want to recommend is to build an app, whatever you choose to build will be fine, if you cant think of anything try too replicate one app that you like and build it with your own touch. This is the best training you will get, its essential to make mistakes and correct them, write bad code and refactor it and just get experience programming and developing apps.

Mímir's well

So now you have some basic knowledge and experience in iOS development. Where to go from here? There is a lot of places you could go too learn some bad some good. But the ones I'm gonna talk about are what I consider some of the best recourses online. You owe it to yourself to at least check them out if you are interested in developing your skills as a iOS developer.


“NSHipster is a journal of the overlooked bits in Objective-C and Cocoa. Updated weekly.”

Just because its overlocked doesn't mean you wont need it or that it is not important. This is a must for anyone who loves too go one step beyond or learn new stuff.

“A periodical about best practices and advanced techniques in Objective-C.”

This is a relatively new site that I have come too like very much. The design is simple and the content is good, very good! One issue a month and every issue will cover one specific subject. Im looking forward too what this project will bring and so should you.

iOS Dev Weekly

You should sign up for this newsletter, it will keep you up to date whats new in the world of iOS development and links to awesome articles and libraries.

Apple developer Videos & Documents

You probably already know about these videos and texts and maybe you have even watched/read some of them. The thing is that I first watched/read them when I was new to the whole programming thing and they only confused me. But when you have the basic knowledge in iOS development these videos/texts are a must watch/read, but only watch/read the ones in what you're interested in or you'll be stuck watching/read videos/texts for a long long time.


I'm a big fan of the podcast format. I can choose what I like to listen too and when to listen to them. The downside is that you have to find the good ones and then find time too listen to them. Ill help you with the first problem by recommending three podcasts I've found really enjoyable.

These are podcasts mainly for iOS developers and sometimes get very geeky so if you're not an developer these may not be for you. But if you are a developer there will give you insight in what problems other iOS developer have had and how they solved them.


This is a podcast where every episode contains of Guy English and Rene Ritchie talking to a developer. It gets personal and gives you and insight in how they work and look at problems and solutions. What makes it really interesting is that they explore many small topics that may be overlooked like pricing and consistently of design of apps you develop.


This is a very nice podcast that aren't afraid to talk about the technical stuff and thats its strong point and weak point. If you have no experience with the subject they talking about it can be hard to keep up with what they talk about but if you can follow everything they saying its very rewarding. So my tip is too read up on the weeks subject a little before listening.

Software Indie

I don't know what to say about this one, sometimes the podcasts last 10min sometimes 1h30m and sometimes its just Scotty talking and sometimes there is a guest or two. The only thing you can be sure of with this podcast is that its very good and I look forward too every episode.

Honorable mentions

How Do I Declare A Block in Objective-C?

Accidental Tech Podcast

75 Essential Tools for iOS Developers

Thanks to all these resources I have learned a lot and keep learning still. I am at the moment busy with school that have just started but I am also working on my new game and a redesign of both code and user experience of my old app. And with iOS 7 just around the corner I think its gonna be an exciting year.

Learn to code

My first attempt trying to become a programmer was when I was about 16 years old, I singed up for two programming classes in high school. After barley passing the first one i knew that this was not for me. It was boring, hard and there where little payoff. Nine years later i give it another try as it was mandatory for the collage degree i was taking. What I found out was that I found the coding was very fun and intressting and that the rest of the classes was boring as hell. So i stopped with that degree and I am now trying my luck in computer science.

So why didn't i like programming the first time? I think it was because I didn't know what to except, I thought it would be easy just because I know my way around some computer software, but I was so wrong. So for all people who wanna learn coding I'm gonna give you a pice of my mind about the subject and will even give you a road to follow if you wanna be a iOS developer.

First I wanna give you a warning and tell you that coding is hard, takes a lot of time and in the beginning you won't understand anything. But thats okay, coding is like nothing other you've done before. Its like learning math and latin at the same time, or at least it feels like it sometimes.

If that has scared you a little I wanna give some soothing words and make you excited about coding. Now that you know that its not a walk in the park and that everyone fells stupid in the beginning it will probably be a lot smother going through the motions.

So you wanna learn to code, well where should you start, maybe with a book? I think thats a bad idea and let me tell you why. Most books are big and intimidating and it wants you to write the code in the book in a text editor and then compile it. Thats a big hurdle to get over in the start. You should concentrate on learning to code and not how to turn your text in a editor into machine code, thats something you will learn later.

So i think the best place to start is Codecademy. Its a great website thats lets you concentrate on the code and learning and forget about compilers, text editors and files. It gives you a place to write code, instructions what you should do and challenges to test what you learn. Every lesson is short and consist and you also get badges when you complete them. Its a very fun and addictive site.

And now to my finale, learning iOS. If you follow these instructions in this order i think you will become a great iOS developer. If you are an experienced developer many of these steps are not necessary. These steps are for the beginner or first time coder. And the reason I have so many steps is that i belive that no teaching is perfect and experience as many different explations of the same thing will make it easier to understand and grasp it. And by doing all these steps you will also get recaps of some important stuff like MVC which is great.

  1. Codecademy - Learn the basics, maybe try Python.
  2. Objective-C Programming: The Big Nerd Ranch Guide - Now its time to be comfortable with xCode and Objective-C.
  3. Code School: Try iOS - This is like Codecademy but better, it has videos between challenges and great slides. Its very much worth the money it costs.
  4. Tinker Learn - Go through their lessons 0-5, if you have completed the Code School course they will offer you  a discount.
  5. Code School: iOS Operations Models - More of awesome Code School.
  6. IOS Programming: The Big Nerd Ranch Guide - This book is great and challenging.
  7. Coding Together: Developing Apps for iPhone and iPad - Very good course, its a bit hard if you new to the stuff, but you're not when you've reached this step.
When you have done all those steps, which will take some time. I believe you will have a great foundation of developing for iOS and if you haven't tried to build your first app, now is a great time to start. And to help you keep learning i have collected some of the best recourses to continue your journey.

I hoped I have inspired you or at lest guided you to some new great recourses. If you have questions about iOS or anything else please contact me on twitter or send me an email.

May the 4th be with you!

My first App

I have finally launched my first app on the Apple App Store and though its not selling by the thousands every day it is still very exciting to have launched an app that at least some people have downloaded and hopefully some of them like it. It took me many hours of coding and testing to get this app ready for primetime.

I will not go into detail about the making of the app, i will post about loopholes i went in to, tips for coding iOS apps, recommendations of development stuff and all of my crazy opinions about coding and pop culture in future blogpost.