About my iOS development book…

It’s been almost two years since I blogged on this page. I know, two years is a long break for a person that claims to love “Writing about my everyday coding problems and solutions”. Well, there is a very valid reason for my absence because I have been working on a book! Two actually, but they’re mostly two sides of the same coin. My first book ever is named “Mastering iOS 10 Programming”. It’s been published by Packt Publishing and with it you can learn all the awesome new iOS 10 goodies that Apple introduced last year.

9359 OS_ B05645 Mastering iOS 10 Programming

If you’re about to go ahead and get this book, wait just one more second. As I said, this is my first book and it covers last year’s material. If you want to learn all the ins and outs about iOS that any iOS master should at the very least be familiar with, go ahead and click the image below to get my latest book “Mastering iOS 11 Programming”.


Okay, that was the short pitch. If it’s bit tougher to convince you to get my book, allow me to explain what you’ll gain from reading this book and then offer you the purchase link again. Sounds fair?

When I wrote my “Mastering iOS” books, I really wanted to write a book that I would personally pick up and read. This means that I focussed on creating content that truly prepares you to do a project that will go to the App Store some day. Each chapter features one of several apps that you’ll build throughout the book. The code you write evolves and you’ll refactor your code all the time to make sure it works well and is as easy to maintain as possible. The benefit in this is that you won’t be writing any crazy or contrived code, just to proof a point. If something is truly an edge case, or if you’ll hardly use an API when you’re working on your own apps, this book will only cover it as brief as possible. This ensures that any lesson you learn helps you push your career as an iOS developer forward.

A lot of iOS developers nowadays worry a lot about their application architecture. Do we use VIPER, MVVM, plain old MVC or something else? The answer to a question like that is extremely complex because there are so many variables involved. This is why my book doesn’t cover any of these architectures. You’ll write MVC code since that’s what iOS promotes at its core. However, instead of tossing all code in the view controller like some people do (causing the much feared Massive View Controller), you’ll see how to break parts of your code into sensible modules so that each part of your code is focussed on completing a single task with an implementation that is flexible. Being able to properly separate the concerns in your code will make adapting to new patterns or architectures much easier because you know what good code looks like.

In addition to general purpose knowledge about building iOS apps, you’ll of course read about the notification system that was introduced in iOS 10. No book on iOS 11 would be complete without coverage of ARKit or CoreML, so of course you’ll learn about those topics in their own dedicated chapters. Some of the other frameworks and APIs that I cover are SiriKit, the drag and drop APIs from iOS 11, iMessage extensions and even Spotlight gets some love.

One final aspect of development you’ll jump in to is automated testing. My book will show you a very simple and basic way of testing the modular code you have written throughout the chapters. Also, you’ll see how testing your code can uncover maintainability issues that you can solve by refactoring your code to be cleaner and more testable.

Sounds good? Well, here is that link to my book again as promised earlier.



Enforcing modular code with frameworks in Xcode

Every iOS developer I know dreams of writing code that’s DRY, modular, testable and reusable. While this is a great goal to strive for it’s often quite hard to write code that is completely modular. It just takes one oversight to blow most of the modularity you have achieved right out the window.

One technique that people use to make it easier to write modular code is to try and ensure that a certain part of their code, for instance the networking logic or their models, know nothing about other parts of the app. Again, a great idea but this isn’t really enforced by anything other than you and your team.

Wouldn’t it be great if there was a way to enforce this level of modularity automatically? Well, I have some great news for you. This is entirely possible and once I tried it for myself it was amazing how straightforward the solution actually is to implement. You can add multiple targets to your Xcode project. This can be used to turn certain parts of your code into frameworks which means that these parts of your code live in isolation from the rest of your code.

The outline of setting this up is as follows:
1. Identify code that should live in a framework
2. Add a new framework target to your project
3. Transfer relevant existing code to the framework target
4. Optional if you use Cocoapods: add dependencies to your new target
5. Write code independent from your app
6. Write tests for your framework
7. Use the framework in your app

We’ll go over each of these steps briefly so you get a good feel of how you can adopt this workflow in your own apps.

Identifying code for your framework

The first step to creating a framework is figuring out what code should live in the framework. It isn’t always obvious which parts of your app could be a framework and which parts can’t be. A good way to figure this out is to think about putting a group of files together in a folder. Can you find a couple of related classes that could happily be put together in a folder where they could only be aware of other classes in the same folder? If you can, it’s probably a good idea to put those files together in a framework.

Another way of finding code that could be better off in a framework is by looking at your code. Are there certain parts of your code that are littered throughout your project that would make changing certain things really hard? That could be a problem in the long run and it might very well be that you actually made some decisions along the way that have destroyed the modularity of your code. Moving some of this tightly coupled functionality into a framework could help you rethink the structure of this tight coupling and it could improve your code drastically.

Adding a framework target in Xcode

Once you have figured out which part of your app you want to put in a framework you need to add a new framework target in Xcode. The easiest way to do this is by going to your project’s settings by clicking on your project name in the Project navigator. Next, look for the + button at the bottom of the panel that lists your targets. This will present you with the same dialog that is presented when you create a new project. In the left sidebar pick the Framework & Library option and select Cocoa Touch Framework.

Now confirm your choice and create the framework by following the on screen steps. If you want to write tests for this target, which you should, make sure to select the Add Unit Tests checkbox. After creating your framework, it is automatically linked to your main app and two new folders were created. One for the framework and one the framework tests.

Adding code to your framework

If you are transferring existing code to your framework, drag the files from your main project folder to the framework folder so your code is logically organised. Next, select the files you just transferred and open the sidebar on the right side of Xcode. Look for the Target Membership header in the File Inspector. You’ll see that the checkbox next to your app is checked. Uncheck this checkbox and check the one next to your framework’s name. This will link the code to your framework instead of your main app.

When you create new files, make sure that the Target Membership is set correctly. Usually Xcode is smart enough to see which folder is currently active and it will add the code to the correct target. It’s always a good idea to double check because you don’t want to go hunting for issues only to find out you forget to correctly set the target for your files.

Integrating with Cocoapods

There’s a good chance your framework has some dependencies. If you’re writing an API framework, you could have a dependency on Alamofire or maybe SwiftyJSON. Cocoapods only links to one framework at a time so your Podfile needs to be updated so it can handle your new framework target. Setting up a Podfile with multiple targets can be done with the following skeleton.

This is very similar to the Podfile you probably already have, expect it has one more target; your framework. Cocoapods will set up your framework target just like it sets up your app, you don’t need to do anything special if you’re adding Cocoapods to a framework.

Writing code independent from your app

Now that you’re all set up, you can start writing your framework code. You do this the same way you’re used to except there is one major difference. In a framework, any code you want to expose to your main application should be marked as public. Code that isn’t marked as public is considered internal and can only be accessed by your framework. Code marked as private still works the same, it can only be accessed by code that lives in the same file.

The big upside of this is that your app can’t know more about the framework then it should. That’s already a big win in terms of modularity.

Writing tests for your framework

Because your tests can only access the public code in your API it’s wise to use your tests as the place where you develop and test your framework. By this I mean that your tests will be the first client that uses your framework. Developing your framework like this makes sure that your framework has great test coverage and you’re testing your framework in isolation from the rest of your app. This forces you to think about your framework instead of the entire app.

Using the framework in your app

Since Xcode has already linked your framework to your app, using your framework works just the same as using any other framework you’ve used. Any file that uses your framework needs to add an import for the framework at the top of the file and from that point out your framework is available to rest of your code.

In conclusion

As you’ve seen, adding your own frameworks to your project isn’t very complex and it forces you to think of your app in a different way. Instead of creating an app where any object can use and access almost any other object you’re creating an app and one or more frameworks. Each of the frameworks you create can function independent from the rest of your app. This means that you could eventually add the framework to other projects or even open source it if you’d like.

Testing your framework is also a lot easier because you know which parts of codes are the API that’s public and those should be the first parts you test. If all you write tests for is your public API, you know that using your framework should work as expected and intended before you even use it in your app.

The approach outlined in this post is especially useful if you only want to use your frameworks in a single app. Using them in multiple apps would require a slightly different approach because you would want the frameworks to live outside of your main project but the benefits and most steps should be very similar.

If you have any feedback, questions or want to discuss this post with men feel free to reach out on Twitter or in the ios developers slack channel

Surviving a start-up’s bankruptcy

On a Tuesday almost two months ago, near the end of april, me and my coworkers received an email about an important meeting the next. We knew that something was going on, the look and feel of this email wasn’t the same as usual. This one seemed a bit darker, a bit more serious. On Friday you could feel the tension in the office, people were speculating a bit and just acting different than usual. But we all had jobs to do and we tried to do them just like we always did. But it turns out that this tension and the feeling we al had wasn’t wrong.

When the meeting actually went down we heard that an investor had backed out of our start-up. Resulting in an inability to pay the bills and sending all of us home until we would know more. What followed was a pretty strange, exhausting and tough period where I learned new things about myself, my work and how to keep busy. I would like to share this experience with you in this blogpost to try and explain how weird of a period bankruptcy can be from an employee’s perspective.

Stage one: registering the events that happened

Since the big announcement was made on a Friday, we actually had a few drinks afterward. It was different than usual, but we had fun, we laughed, talked about how much of a great time we had and that it wasn’t over just yet! We could still be bought, an investor might pop up soon and we’ll all be back to work in no time. Then Monday came along and I didn’t have to go to work. There really wasn’t much for me to do actually. So I started my week with just taking the day off. In the back of my mind I had this idea that I was getting payed anyway, so I might as well enjoy this time off.

At first I did pretty well, the first couple of days were pretty laid back, I started working on a side project called “Cijfer Hulp”. It’s a simple app for Dutch students to keep track of their grades and what grade they need to maintain a great average. But after a couple of days I realised that my job probably wasn’t going to come back. This was a pretty huge blow, I loved my job! I enjoyed going there every single day, and to realise that a 10 minute meeting was the last thing I’d ever do at this company was a pretty big blow.

Stage two: finding purpose, keep going

When I established with myself that I was probably going to be out of a job soon I started to look for a new job. This went pretty well at first, a few companies responded to my applications rather quick and I had set up some meetings in no time. However, I felt like I lacked a purpose. My side project was finished in about 8 days so there wasn’t much for me to do either. Staying in bed until 10:00AM, 11:00AM or later started to become easier and easier and falling asleep at night became harder and harder. I grew frustrated and irritable very quickly and while the meetings with potential employers were fun, they didn’t give me a sense of security.

The fact that I had no job, a few potential employers and the possibility of choosing one to work for and not knowing when I would know more about my current job was troubling me. One of the things that kept me thinking was the fact that my current employer still didn’t officially go bankrupt. We were all sitting at home, waiting for the court to pass a verdict. Three weeks went by with no news. It was just about time for us all to get payed, but the money wouldn’t come since there was no money. In The Netherlands there’s a company that will take over all of the salary payments from an employer if they can’t pay anymore, but this only happens after the court has declared bankruptcy. At this point it was clear that verdict would have to become bankruptcy. It was just a matter of when.

During this first month I had days where I was just frustrated, grumpy and tired all day. Keeping myself busy just felt pointless. I lacked purpose, everything I did was just filler to get through another day of not having to do anything. On other days I was motivated, I though about maybe going freelance or starting another side project. These days were quite fun actually because they had purpose and meaning. Whenever I’d go and have a cup of coffee at some company I always felt pretty satisfied, I was working towards something. However, my overall mood wasn’t too good. Having no responsibilities or purpose is taxing and I wouldn’t recommend it to anybody. Doing small side projects is a smart idea. What also helped was to just head out of the house around 09:30 and go to the library to work there. Whenever I did this I was at least double as productive compared to staying at home all day.

Stage three: something look forward to

After a little longer than a month I found an employer that I wanted to work for. And they were excited to hire me as well! This felt like a huge win. No matter what was going on at my current job, I knew what was next. And the best part, just a few days after this I also got the news that me and my coworkers were now officially fired and the company had been declared bankrupt. However weird it may seem I was very relieved with this letter. Finally some closure, finally a timeline for it all. Just one more month and then I would start at my new employer, knowing that the current situation would be fully handled and I could finally start working towards getting the salary I still needed from the month of sitting at home. All of this had been so frustrating, especially not knowing what’s next and when it was coming. So for all of this to fall in place so short after one another was truly a blessing.

Tips for people who might find themselves in a similar situation

My most important tip is to try and keep up some sort of schedule. Your work rhythm probably provides some stability to you and your mind. Don’t break this, try to go to a public library or if you’re comfortable working from home, try to spend the day working on things. Maybe a side project, maybe some blog posts or maybe do some chores that you needed to get done anyway. You don’t have to spend your whole day programming, just make sure you’re busy.

Also, i would recommend to start looking for jobs right away. Just go and have some cups of coffee with people. You don’t have to formally apply everywhere, just get to know some people. Expand your network. It might seem a bit pointless and hard at times, but it’s really worth it. The nice thing about being in this situation is that there’s no rush in finding a new job. You can take it easy, you can really browse around for a nice place to work at.

It’s okay to be sad or feel down about the situation. When I had a bad day sometimes I thought that I had messed up. I should have been able to see this coming or do something, or whatever. It’s tough to realise that it’s something you might not have been able to see coming, something that you lack control over and it’s okay to be bummed out. If you loved your job it will have huge impact on you when that suddenly disappears. This is also the reason why I recommend to try and keep up our rhythm. It will help to keep your mind from wondering and it will help you wit that feeling of having no purpose.

Clean derived data from Xcode, the simple way

Any iOS developer that has spent significant time with Xcode is familiar with at least a couple of it’s caveats. Random crashes, slowness, autocomplete not working for a few seconds and build errors right after you’ve added or removed a library. Or, just a random appearance of 200+ warnings like I had just now. The solution for quite a few problems with Xcode’s building process can be found in clearing out your derived data. In the past I would always fire up a new terminal window, type in something like open ~/Library/Developer/Xcode/DerivedData/ and then manually clearing out the folders I think aren’t needed. But today I found out that Xcode has a built in fix-me button, right in your project organizer!


All you have to do is go to the project organizer (window -> projects) click the button that’s outlined and you’re done. Any issues with your derived data should be cleaned up (for now) and your Xcode should stop complaining about silly things for a while now.

Happy coding!

Wrapping your callbacks in Promises


A little while ago I wrote a post about PromiseKit. In this post I wrote mainly about how you could wrap API calls in Promises using the NSURLConnection extension that the creator of PromiseKit provides. Since writing that article I’ve had a bunch of people asking me more about PromiseKit. More specifically, some people wanted to know how they could wrap their existing code in Promises. To illustrate this I’m going to use Parse as an example.

A regular save action in Parse

Before we start making Promises, let’s have a look at how you’d normally do something with Parse. An example that any Parse user probably has seen before is one where we save a PFUser.

Above code should be fairly straightfowards. First we create a user, then we call signUpInBackgroundWithBlock and then we specify the block that should be executed after the user has been signed up. A lot of Parse’s save and fetch actions follow this pattern where you use callbacks as a means to handle success and error cases. In my previous post I explained that Promises are a cleaner method to deal with asynchronous operations, but wrapping something like signUpInBackgroundWithBlock in a Promise isn’t very straightforward.

Creating a custom Promise

Setting up a Promise isn’t very hard. What you’re going to need to decide on in advance is what your Promise is going to return. After that you’re going to need to figure out the conditions for a fulfilled Promise, and the conditions for a rejected Promise. How about a simple example?

The function above returns a Promise for a String. When you create a Promise you get a fulfill and reject object. When you create your own Promise it’s your responsibility to make sure that you call those objects when appropriate. The doSomething function receives a Bool this flags if the Promise in this example will succeed. In reality this should be dependent on if the action you’re trying to perform succeeds. I’ll show this in an example a little bit later. If we want this Promise to succeed we call fulfill and pass it a String because that’s what our Promise is supposed to return when it’s succesful. When the Promise should be rejected we call the reject function and pass it an ErrorType object. In this example I chose to create an NSError.

Now that we have explored a very basic, but not useful example, let’s move on to actually wrapping a Parse call in a Promise.

Combining Parse and PromiseKit

When you’re doing asynchronous operations in Parse you call functions like ‘signUpUserInBackgroundWithBlock’. This function takes a callback that will be executed when the user has signed up for your service. Let’s see how we can transform this callback oriented approach to a Promise oriented one.

In the example above a function is defined signUpUser, it takes some parameters that are used to set up a PFUser object and it returns a Promise. The next few lines set up the PFUser and then we create (and return) the Promise object. Inside of the Promise’s body we call signUpInBackgroundWithBlock on the PFUser. The callback for this function isn’t entirely avoidable because it’s just how Parse works. So what we can do, is just use the callback to either call reject if there’s an error or call fulfill when the operation succeeded.

That’s all there is to it, not too complex right? It’s basically wrapping the callback inside of a Promise and calling reject or fulfill based on the result of your Parse request. One last snippet to demonstrate how to use this new function? Sure, let’s do it!

The way this works is basically identical to how I described in my previous post. You call the function that returns a Promsie and use the then and error (report in an earlier PromiseKit release) to handle the results of the Promise.

Wrapping up

In this post I’ve showed you how to take something that takes a callback and wrap it in such a way that it becomes compatible with PromiseKit. The example was about Parse but this principle should apply to just about anything with a callback.

The only thing I didn’t cover is where to actually implement this. I did that on purpose because it really depends on your architecture and partially on preference. You could opt to put the wrapping functions in a ViewModel. Or you could create some kind of Singleton mediator. Or maybe, and I think I prefer this method, you could write some extensions on the original objects to provide them with functions like saveUserInBackgroundWithPromise so you can actually call that function on a PFUser instance.

If you’d like to know more, have questions or have feedback, you can find me on Twitter or in the (amazing) iOS Developers Slack community.

Step up your async game with PromiseKit

Some of the most engaging apps we use today are apps that require network connectivity of some kind. They communicate with an API somewhere to fetch and store data for example. Or they use an API to search through a huge amount of data. The point is, you don’t want your application to sit around and wait while an API call is happening. The same is true for a computing task that’s heavy, for example resizing an image or storing it to disk. You want your UI to be snappy and fast. In other words, you don’t want to do your heavy lifting on the main (UI) thread of a device.

Taking something off of the main thread

There’s several ways to take something away from the main thread. An NSURLConnection automatically performs requests in the background and uses delegates to make callbacks about progress or completion for example. You can also use the dispatch_async function to make something happen on a different thread. While this works perfectly fine it’s not very ideal. When an NSURLConnection performs it’s delegate callbacks it has to be coupled to that delegate. Also, imagine you want to chain together a couple of network requests; it will start to become kind of messy to keep track of everything.

Now imagine an object that you can pass around, it will automatically perform a task once it’s done what it’s supposed to do. These tasks can be chained so if you want to chain multiple things together it’s very simple. Or maybe you want your callback to fire only if a couple of tasks are complete. Imagine implementing that with multiple NSURLConnections. You would probably have multiple instances and whenever one is complete you check the status of the others and then when all are complete you can actually execute the code you’ve been meaning to execute. That sounds a lot more complicated than just writing:

The above snippet is actually really close to how PromiseKit works. Let’s explore that a bit further, shall we?

Note: I am going to apply PromiseKit to network requests for this post. The concepts actually apply to anything that you want to do asynchronously.

A simple Promise example

To demonstrate a simple Promise we’ll make a network request. First we create an NSURLRequest that we’ll pass to an NSURLConnection. Then we kick off the loading with a Promise so we can use the result once the request is done:

PromiseKit has provided us with an extension on NSURLConnection that allows us to call promise(req:NSURLRequest) on it. After that we call then. The code that’s inside of this closure gets called once the Promise is fulfilled. This happens whenever the request completed with success. If the request fails we can add a report (‘catch’ in swift 1.2) as well to make sure we catch that error:

And if there’s code we want to execute regardless of error or success we can use ensure (defer in swift 1.2) like this:

If you understand this, you basically understand all you need to know to start using Promises in a very basic way. But let’s get a little bit more advanced and start returning our own Promise objects.

Returning Promises

Imagine this, we’re building an application that uses an API. We want to ask the API for a user’s feed and we want to use PromiseKit for this. A nice implementation might be to have an API instance that has a method on it called fetchUserFeed. That method will return a Promise so we can easily use the result from the API in the class that actually wants the API to fetch data, a ViewModel for example. The fetchUserFeed function might look something like this:

Note: Feed is a just a data object not included in the sample for brevity. It is used to illustrate how you would return something from a Promise

The function above is very similar to what we had before except now it returns NSURLConnection.promise which is a Promise. The then of that Promise now returns a Feed and the fetchUserFeed function now returns Promise<Feed>. What this means is that fetchUserFeed now returns a Promise that will resolve with a Feed. So if we use this function it looks like this:

That’s pretty clean, right? Now let’s say that we not only want to fetch the Feed but also a user’s Profile. And we want to wait until both of these requests are done (and successful). We can use the when function for that:

Let’s make this this a little bit more complicated shall we? Currently we’re able to use an API to fetch stuff, and we’re able to do multiple requests and wait until they’re all complete. Now we’re going to wrap that into a function we can call from somewhere else. The function will return a single object that uses both a Feed and UserInfo to create itself. Let’s call it ProfileModel.

And when we want to use this function we would write something like this:

That’s pretty cool isn’t it? Pretty complicated logic wrapped in promises to make it simple and enjoyable again.

Wrapping it up

In this post we’ve touched up on the basics of PromiseKit, a library that makes asynchronous programming cleaner and easier. I’ve shown you how to use them in a very simple and basic setting and in a situation where you wait for multiple operations/promises and return a single promise with both results. Promises can help you to build a very clean API for your async operations and they help you to keep your code clean and readable. I highly suggest to try using promises in your own projects, they’re really cool and easy to use. To find out more about PromiseKit you should check out their github.

If you have questions or feedback for me on this subject make sure to hit me up on Twitter or look for me in the ios-developers slack community.

The dangers of forcefully unwrapping values

Whenever I’m programming, I have a goal in mind, generally a problem to solve. I want my solutions to be simple, yet elegant and reliable. Thankfully, Swift is a great language for this. The language is safe, its syntax is beautiful with great readability. The way Swift handles nullability contributes greatly to its safety.

If you want to declare a variable in Swift you can use either the let or var keyword. If you don’t want to assign a value to one of your properties right away you could write something like var episodeName: String?. This informs the Swift compiler that episodeName might not have a value when we’re accessing it. If we don’t add the question mark and write var episodeName: String, the episodeName will need to be assigned a value when we initialize the object that contains this property. A third way to declare episodeName is to implicitly unwrap the value: var episodeName: String!. This tells the compiler that we are 100% sure that episodeName will get a value before we attempt to access it.

These question mark / exclamation mark semantics also apply to using variables in your code. When you’ve declared your variable with a questionmark (var episodeName: String?) we are never sure if episodeName is nil or a String. So whenever we want to use this variable we need to unwrap it. The safest way to do this is as follows:

However, if you’re 100% sure you’ve set a value, you can tell the Swift compiler to stop complaining because you know what you’re doing and you just want to get your episode’s name:

By adding the exclamation mark after episodeName, we force unwrapping it and we can use it’s value straight away without an extra if statement.

Where’s the danger?

If you’re writing an application you’re sometimes sure that you assign a value to something. For example, you might have written something like:

This code should usually be safe. Before we ask the show for it’s episodeName we actually set it so we’re always sure that episodeName has a value before we access it. So the implementation of printEpisodeName might be:

This shouldn’t throw errors. After all, we know what we’re doing! We always set the episodeName right after we instantiate our class. What could go wrong, right? Well… besides the fact that we probably should have created an initializer that takes the episodeName, a lot can go wrong.

Honeymoon’s over..

So, our project has been ongoing for a few weeks and we’re changing the API. Before, we were guaranteed that the API would always return properly formatted JSON but we’ve decided that things like the name for an episode isn’t guaranteed anymore. In other words, the name can be nil.
We test our app, everything still works when we’re navigation to our show page so we’re happy. But then.. crash reports come in. Users are livid and to add insult to injury, your manager is suddenly next to your desk. The app is crashing. Hard.

What’s going on!? Everything was fine before! So we start searching and debugging. And once we manage to reproduce the error we see what’s going on:

And then we remember. The forcefully unwrapped optional in our TVShow class:

When we set the episodeName on our tv show, the name we get from the API can be nil. And that’s alright because we declared our episodeName like this: var episodeName: String?. Which means that episodeName can be either nil or a String. Luckily, our bug is easily fixed:

Now we handle the optional value properly, we avoid crashes and an angry manager. Time to get yourself a cup of coffee and tell your manager that you’ve fixed the error.

The takeaway :)

As we saw in this post it can be tempting to force the unwrappin of a variable when we’re pretty sure that we will set it before we use it. But as requirements change it can be easy to overlook situations where a variable can suddenly be nil when we try to access it.

My advice is to (almost) always unwrap optionals properly with an if let construction. It’s the only way to be 100% sure that you’re not accidentally accessing a variable whose value is actually nil. More importantly, this will help to prevent future crashes.

So remember kids, always unwrap your optionals in a safe way.

High performance shadows for UIView

No app is truly complete without some subtle shadows. Especially now that Google’s Material Design is showing us that shadows are cool again we need a way to properly add them in our apps. In my previous post I wrote about a way to create a custom UICollectionView layout. There was one problem with that post though, that shadows are incredibly heavy on the iPhone and scrolling stutters.

So can we fix this? The answer is yes and the solution is (surprisingly) easy. A Google search led me to this Stackoverflow question about shadows. The solution I tried first was to simple rasterize my layer but that wasn’t what I was looking for. Images started to look very bad and I didn’t want that. Another solution that was proposed is to supply the  layer with a  shadowPath.

What is shadowPath and what does it do?

If you set the  shadowPath property it will function as a guide to the shadow that ends up underneath your view. If you don’t set this, the view need to be analyzed at runtime to determine where the view is transparent and where it isn’t which will result in the eventual shadow shape. This is a pretty costly operation, especially if you do this for about 20 views at a time in a UICollectionView. And even more so if you start scrolling in this view.

Implementing shadowPath

Assuming we’re using the code from my previous post there isn’t much we have to do. We have to create a circular path that has the same size as the imageView. We know that our  imageView get’s rendered at 80px by 80px so we can use  UIBezierPath with rounded corners to generate a circular path. Let’s add this line before we specify the shadows in the  CustomCollectionViewCell class:

Build and run the project and you should now see butter smooth scrolling instead of the bad scrolling we had before.


If you want to use shadows on your views then you should probably also set the  shadowPath on your view to ensure proper performance. By doing this you can speed up rendering a great deal because otherwise the view will be analyzed at runtime to find out what shape the view has, this is a lot slower than just providing the proper shadow path. Setting the path does not only increase performance but it also allows you to create many fun effects with shadows.

Creating a custom UICollectionViewLayout in Swift

If you’ve ever built an iOS app that uses some kind of grid layout or displays a list in a way that doesn’t fit a UITableView you have probably used a UICollectionView. This components allows for very simple grid layout creation and it even allows you to dynamically change layouts. This component becomes even more powerful and flexible if you create your own layout by subclassing UICollectionViewLayout.

Recently I had to build a kind of playful, almost grid like layout. To me this seemed like the best time to dive straight into subclassing the UICollectionViewLayout and create a nice layout. In this post I will explain how I did it and I’ll provide you with a little bit of code so you can start building your own layouts in no-time.

The end result

Since I’m a great fan of cats, we’ll be building a collection of cat images. The images will be rounded, they’ll have a nice shadow so they look kind of nice and the magic bit is, of course, the slightly offset rows that we could realize because we’re using a custom UICollectionViewLayout.

Schermafbeelding 2015-07-07 om 20.57.24The image above illustrates what we’ll end up with when we’re done. It’s amazing, isn’t it?

Initial set-up

Before we get to build our layout we have to do some set up. I created a new XCode project and selected the Single View Application template. I named my project “CustomCollectionViewLayout” because I’m not very good at coming up with names. You can name your project anything you like.

Step one: setting up the interface

Creating the UICollectionView

The first thing you should do is open up the Main.storyboard and drag a UICollectionView out to your View Controller. When you’ve done this give the UICollectionView a white background color and add constraints to it so it will fit your view nicely. If you’re unsure how to do this, size the UICollectionView so that it touches the left, bottom and right edges of the view and it should be aligned underneath the status bar. XCode should provide you with some helpful guides for this. Once your view is sized like this, click in the bottom right corner of your canvas and choose “Reset to suggested constraints”.

Schermafbeelding 2015-07-07 om 21.07.21

Next up, we should connect our UICollectionView to our ViewController class. Open up the assistant editor by pressing the two overlapping circles in your XCode window and make sure that the editor is set automatically use an appropriate file.

Schermafbeelding 2015-07-07 om 21.25.52

Select the UICollectionView, hold ctrl and drag over to the code editor to create an outlet for the UICollectionView. I named mine “collectionView”. That’s all setup we need for now.

Creating a UICollectionViewCell

To display our cat images we need to have a UICollectionViewCell with an image inside of it. To do this we can simply create our own UICollectionViewCell and put a UIImageView inside of it.

First, create a new CocoaTouch Class (either press cmd+n or by navigating through the file menu). Name your file CustomCollectionViewCell, make it subclass UICollectionViewCell and check “Also create xib file”.

Schermafbeelding 2015-07-07 om 21.14.25

XCode should have created a .swift and .xib file for you. Let’s open up the .xib file first and then press the assistant editor button so we have both the .xib and .swift file open at the same time. Drag a UIImageView out into your custom cell and size it so that it fill up the cell exactly. Since we’ll be resizing the cell later we should “Reset to suggested constraints” again, just like we did with the UICollectionView earlier. Now select the image, press and hold ctrl and then drag to your swift file to create an outlet for the imageView. I named mine “imageView”.

Our example image had rounded corners and a shadow applied so let’s write some code to make this happen. All you need is a few lines inside  awakeFromNib().

This code is fairly straightforward. First we apply rounded corners to our imageView. Then we apply a shadow to the cell itself. You can tweak the numbers to change how the cell looks. Did you notice the magic number  40? In an actual app you might want to find a better solution for this because 40 is half of the cell’s eventual size but there’s no way to know that unless you came up with all the sizings yourself.

The last thing we have to do is register this custom cell to our UICollectionView. We created an IBOutlet for the UICollectionView earlier by ctrl+dragging from the UICollectionView to the ViewController. Open up  ViewController.swift  and add this line to the  viewDidLoad method:

We’re using a  cellIdentifier  variable here, let’s define that as well. Place this code right below your collectionView  outlet:

Allright, that’s all. Our UI is fully prepared now. The code you’ve added to ViewController.swift  should look like this:

Step two: setting up the UICollectionView dataSource

To get our UICollectionView to display our collection of cat pictures we will need to make sure our UICollectionView knows where to go for it’s data. To do this, select the connections inspector in the right drawer of XCode and drag the dataSource connector to the ViewController class.

To actually implement the dataSource we should make our ViewController  comply to the UICollectionViewDataSource  protocol. Open up  ViewController.swift  and change it’s class definition to this:

By adding  UICollectionViewDataSource  after the superclass we tell Swift that this class implements the  UICollectionViewDataSource protocol. This protocol dictates that we should at least provide our UICollectionView with:

  • the amount of sections it should contain
  • the amount of items there are in each sections
  • cells to display

The following code takes care of all this:

Our collection will contain a single section with 50 items. Our cell creation code is also fairly straightforward, we dequeue the cell that we’ve registered earlier and we forcefully cast it to be a  CustomCollectionViewCell. Then we set the  imageView.image to one of the cat images I added to my project earlier. I only added 10 images so I reuse them. To use this code you should add 10 images to your  Images.xcassets and name them cat_0.jpg – cat_9.jpg.

If we were to run our app now we’d end up with something like this:

Schermafbeelding 2015-07-07 om 21.42.30

Not quite what we wanted.. but don’t worry, we’re going to implement our custom layout right now!

Step three: implementing the custom layout

Now that we’re all set up it’s time to get to business. First, create a now Cocoa Touch Class and call it “CustomCollectionViewLayout”. It should subclass  UICollectionViewFlowLayout. To avoid many small chunks of code I’ve grouped together some code in sensible groups, I’ll show you code first and then explain what it does right after that. Let’s get going with the first chunk:

This first section is responsible for the initial setup. It sets up some sizing values (remember that magic number 40 in our cell?) and it creates an array that we’ll use to store our layout in. When you’re creating a collection view that changes often or contains a lot of items you might not want to use this technique but since we have a relatively small collection that doesn’t change often we can cache our entire layout. There’s also a variable to hold the maxXPos , we’ll use that to calculate the collectionView’s content size later. In the  setup() function we configure the layout, these properties are inherited from the  UICollectionViewFlowLayout and allow us to set up spacings and a scrollDirection. In this case we’re not really using the spacings but I think it’s good practice to set them up anyway.

This piece of code comes after our initial setup, it overrides the prepareLayout  function which is called before the cells are actually going to need their layout. This allows us to pre-calculate our entire layout. Which is exactly what we want to do for this use case. There’s a loop inside this function that uses the  collectionView.numberOfItemsInSection function to find out how many items it is going to display. It then initializes layoutAttributes for the item at the current NSIndexPath and it calls  frameForItemAtIndexPath. To calculate the item’s frame. Next up is a check to determine of the x position for this item is the largest x position in our collection and then it stores the itemAttributes in our layout cache.

The  frameForItemAtIndexPath function uses the height of our collectionView to determine the amount of cells it can fit into a single column, then it determines how many rows there will be in our collection and based on that it calculates the x and y position for the item. Every other item will be offset somewhat to the right, we use the % operator and a ternary for that. If  currentRow % 2 == 0 the xPos is equal to  currentColumn*(itemWidth+self.minimumInteritemSpacing), otherwise it will be equal to  currentColumn*(itemWidth+self.minimumInteritemSpacing)+itemWidth*0.25. And finally we return a CGRect with the correct size and position values.

This last snippet of code actually provides our collection with the layout:

The first method,  layoutAttributesForItemAtIndexPath simply returns the layout attributes that belong to the passed IndexPath. Fairly straightforward. Next, we have  layoutAttributesForElementsInRect. This method is somewhat more complex because we get passed a  CGRect and we have to determine which items are inside of that area. To do this we loop over our layoutInfo object, we compare the rects and we return all intersecting items.

Finally, we calculate the collectionView’s contentSize. The contentWidth is equal to our  maxXPos + itemWidth and the height is the same as the collectionView’s height.

Step four: using the custom layout

The final step in this tutorial is to actually make the UICollectionView use our custom layout. To make this happen, select the Collection View Flow Layout object that is associated with your UICollectionView in your Main.storyboard and change it’s class to  CustomCollectionViewLayout.

Schermafbeelding 2015-07-07 om 22.14.33


Now build and run your app, you should see something like the image I showed you at the beginning of this post.


In conclusion

I hope this post is helpful to some of you out there. I had a lot of fun today figuring out how to do this myself and I figured there’s probably more people out there who are looking for cool ways to implement UICollectionView and use custom layouts.

The code for this project can be found on GitHub and if you want to reach out to me, I’m on Twitter.

Find every other element in an array with Swift

The other day somebody asked how they could retrieve every other element in an array using Swift. The solution they had tried was to use a for loop to go through all of the elements and then they would pop those elements off the array.  This seemed to work okay but only when all elements would be subsequent to each other. So an array like [0, 1, 2, 3, 4]  worked fine but when an array looked like  [90, 67, 45, 22, 123, 32] this approach didn’t work.

Luckily, swift has an enumerate function that allows you to loop through an array with both an index and the array value. The solution I eventually came up with was to enumerate the array and get the remainder from dividing the index by two in my loop. I then used that to determine if it was an even er odd index and then I printed the value of the element in the array. This might sound complex but the snippet is short and simple:

Simple enough, right? The enumerate function provides us with a way to loop through an array and get an index easily. That way we can write a clean for loop without doing something like var i = 0; i < array.count; i++ for example.

If you have questions about this you can send me a tweet and I’ll try to help. Happy Swifting!