17 Kwi

Getting off the beaten track

Every software developer has a set of programming habits that he or she has built over time. I’m talking about naming convention, code formatting rules, favourite language structures, design patterns, etc. Show me the code and I’ll tell you who of my work colleagues is to blame, without using tfs annotate feature ;) Well, I’m right most of the time :) The best compliment I ever got was from my former team leader, who once said he couldn’t tell if the piece of code had been written by him or me. He’s my guru so this was a really nice thing to hear ;)

In the last years I’ve been working mostly with silverlight, windows phone and windows universal apps and I have developed my own habits. Whenever I’m facing an issue with my current app development in Swift, I’m thinking about the problem in a c# way. This is actually pretty understandable, since I’m new in iOS programming world, I can’t think differently. Then I start to google, find similar question and I wonder about the answer :) I wonder, I wa wa wa wa wonder :) So today I wondered about lack of events in Swift, at least the kind of events I know from c#.

I’m developing Magic hours in Model-View-Controller architectural pattern. This is when view controllers serve as the communication pipeline between views and data model. I’m used to Model-View-ViewModel, but I thought MVC would be easier for the start. So I did some refactoring today and moved the code responsible for getting user’s current location from my view controller to a new class representing whole application model. Since it’s asynchronous and I cannot access UI elements from my model, I thought the best approach would be to define some kind of completed event, that will be raised when the location will be known and to subscribe to this event in my view controller. I googled this blog post: implementing events in Swift. The author says: C# developers have the luxury of first-class language support for events, however in most other mainstream languages this is something that is either provided at a library level or that you have to implement yourself. Implement yourself? Not good ;)

After investigating further I found this stackoverflow question. Looks like someone is having same problems :) The answer with the most votes helped me to came up with a working solution. I really like what the author wrote as this sums up what this post is all about:

Different platforms do things differently. If you are thinking How do I raise an event in my business logic class that my ViewController can subscribe to … ? you are going to be fighting the frameworks and have both a hard time and overly complicated code for it. Instead, what you should be asking is more along the lines of How do I know when an asynchronous operation has completed?

So I went in for delegates and closures. I’ll explain what’s happening in my code in one of my next posts. In the meanwhile – check out my github project.