Brave Location Mobile Apps and Web Solutions

Baby Steps with Swift

As per my previous posts, I’m developing an iOS app “in the open” using Swift as a learning experiment. It’s going to be an app that counts down the days to a future date.

Data Model design

I thought a good way of getting started would be to work on the data model code. There would be more pure Swift code to write to get up to speed on the syntax, plus I’d get the chance to write some unit tests too.

The data model design is pretty straightforward; I want to have the following properties to hold the settings data:

  • start: NSDate
  • end: NSDate
  • title: String
  • weekdaysOnly: Bool

Then there are three different access properties/methods to calculate various day lengths:

  • DaysLength: Int - the number of inclusive days between the start and the end
  • DaysGone(currentDate: NSDate) -> Int - the number of days from the start to the current date
  • DaysLeft(currentDate: NSDate) -> Int - the number of days to the end to the current date

Swift strangeness

Writing a simple class to implement this logic was pretty simple even in a new language, although a few things were a little strange at first in Swift.

Semi-colons at the end of the line are optional in Swift, and a few references I found seemed to say best practice is not to add them, although muscle memory from Objective-C and C# made this hard to do.

Also integrating into the IOS Foundation classes was a little strange in places especially the use of optional values. For example, note the ! at the end of this line

model.start = NSCalendar.autoupdatingCurrentCalendar().dateFromComponents(startComponents)!

My model.start is of type NSDate i.e. can’t be null, whereas dateFromComponents() can return a null value, so the ! forces this to actually return a value (I think!). Not the most intuitive, but thankfully the XCode editor prompted me to add the exclamation point.

The other problem I had initially was being able to reference the DaysLeftModel class from my unit test code. I couldn’t figure out anyway of importing the model code, before this very helpful blog post by Andrew Bancroft pointed out the way of configuring the build settings to automatically create a module.

Date calculations

For the date logic of calculating the difference between two dates ignoring weekends was a little tricky, but as usual the Internet was my friend and with the help of TDD and the algorithm outlined in this article by Alec Pojidaev I managed to get it working correctly.

The code

So I’m happy to be up and running in Swift, and the code is up at GitHub if you’re interested.

Next steps

I think I’ll next tackle storing these settings in a local datastore, as well as synching them with the cloud to share across devices.

Previous posts in the series

The code for the project is also available on GitHub

N.B. This blog post has now moved to