Swift vs Kotlin for real iOS/Android apps

Angel G. Olloqui
18 October, 2016

Swift and Kotlin are two great languages for iOS and Android development respectively. They both have very modern features and syntax that can help enormously to build native apps. But, how do they both compare to each other? Are they similar? Can we reuse more code between platforms if we adopt them in our projects?

Those are the questions we will explore in this post together with some real app code examples implementing the same features in both languages.

Side to side

As commented, both languages are very similar. In fact, they are so similar that I will focus on the differences rather than the similarities in this post. Before exploring the code samples, let’s cover the most relevant ones that will pop up when translating between them:

Swift Enums are more powerful: In Swift, enums are very powerful and first-class type. They can contain different associated values per case (discrete union types), computed properties and most of the features of structs. Because of that, it is frequent to see patterns like the Result enum that are not common in Kotlin due to language limitations (UPDATE: A similar pattern can be implemented in Kotlin by using sealed class instead of enum, but it is more complicated that the Swift counterpart)

Swift has no data class: One interesting construction in Kotlin is data class. It allows you to declare containers of information that automatically implement things like equality and copying. Very common pattern when dealing with plain objects that has no counterpart in Swift.

Swift does not have delegated classes or delegated properties: A very interesting feature of Kotlin are delegated classes and properties. With them, you can forward invocation of methods to another class automatically, or define behaviors for properties such as lazy, obsrvable, etc. You can even create your own property delegates. In Swift, things like lazy are modifiers implemented in the language, so that means that you can not create your own but you are limited to the ones provided.

Swift does not allow annotations: Coming from the Java world, Kotlin has full support for annotations. However, in Swift that is not considered at all, so annotations like @Inject or @Test that are so common in Java libraries do not have any counterpart in Swift.

Kotlin classes are final by default: Kotlin classes are by default closed for extension, so you have to add open in any class you expect to be extended with inheritance.

Kotlin has no struct or passing data by value: In Swift you can decide whether to use a class or a struct for your data. The decision is not trivial, and results in different implementation details. Structs are always passed by value, meaning that every time you call a method with it, return a struct, assign a struct,... the values are actually copied to the new variable, and any modification will only affect the modified variable and not the others. Besides that, structs do not allow inheritance, so they tend to be a perfect candidate for data classes. In Kotlin, there is no struct type and the language follows the same pattern than Java, where basic types (int, float, boolean,...) are passed by value, but the rest are passed by reference.

Kotlin has no tuples: Tuples are not implemented in Kotlin, so you will find yourself creating small data classes as counterpart for Swift tuples.

Kotlin has no typealias: I just found out that it is in the roadmap for 1.1 but at the moment (Kotlin 1.0.4) there is no typealias, so patterns like the one I explained in this previous post are not possible yet.

Kotlin has no guard statement: In Swift, guard statements are a more expressive way for checking conditions of some function than the standard if sentence. In Kotlin, you need to stay with the if check and reverse the condition.

There are also other differences when comparing both languages. Things like exceptions, pattern matching, constructors, if let sentences, loop iteration, casting,… work in slightly different ways, but in general they follow the same principles and they have very similar syntaxes.

One last difference to mention when working for iOS/Android is that the Operating System offers different runtime environments and libraries to developers. A couple of points to highlight:

Memory management: Kotlin assumes the existence of a Garbage Collector (provided by the Dalvik/Art runtime in Android) and therefore memory management is transparent for the developer. On the other hand, Swift manages memory with a Reference Count approach (ARC) so you will need to think about memory ownership and retain cycles.

System frameworks and libraries are very different: When accessing system frameworks or libraries like networking, UI, etc. they both offer very different APIs so the resulting code will look pretty different.

The list of differences might look long, but trust me, the amount of features shared by both is much longer. I suggest you read swift-is-like-kotlin for an extensive comparison of different features of the languages side to side to get the feeling about it and some of the syntactic differences.

MVVM + Rx + Coordinators

OK, so we have some differences in the language and big differences in the system frameworks and libraries, especially in UI. But can we still reuse code? And can we increase code reuse somehow?

The answer is yes, we can still reuse the code, and yes, we can increase code reuse by properly splitting responsibilities and isolating dependencies. In other words, we need to carefully chose a proper SOLID app architecture, because a wrong choice will highly limit the amount of code reused.

There are multiple architectural patterns out there (MVC, MVP, MVVM, VIPER, FLUX,...), each of them with their own benefits/drawbacks and best usage scenarios. I am not going to explore or compare them here because that is out of the scope of this post, but let me quickly review the one that I chose for this sample project: MVVM + Rx + Coordinators.

In MVVM, the code is split in Model, View and ViewModel. Views include UIViewController/Activities/Fragments, while ViewModel is a new entity introduced to map the model into data that can be consumed by the View layer easily. The main benefit of this pattern is that the Model and the ViewModel are completely agnostic from UI, and it is the UI the one that will “listen” for changes in the ViewModel and not the other way around. Code in View layers get shorter, as they do not need to apply any logic but just display what the ViewModel provides. This is a good feature for our case because we mentioned that UI code will be pretty different for both apps, so then we can keep those differences isolated and as short as possible.

The addition of Rx gives us a very powerful framework to “listen” for the ViewModel changes, and at the same time keep consistency between platforms since there are RxSwift and RxJava counterparts following the same conventions. They also have platform dependent additions (RxCocoa and RxAndroid), but we will keep those limited to the View layer.

Finally, I have added a Coordinator layer. This layer is sometimes also called Router, and it basically glues the different parts together and handles the navigation between them. The usage of coordinators helps us building the dependency tree and isolating the navigation logic out of the View layer.

Example code snippets:

For this post we will explore a very simple app consuming the OpenTable API as exposed here. The app will just present a list of restaurants, add some pagination when scrolling to the end of the table, and open a simple restaurant detail. I should also mention that I kept the connector to the API in an external library, not dependent to Rx, in case we want to build a different app without Rx but reusing the OpenTable connector, but we could have added the Rx dependency there as well to simplify the callbacks.

RestaurantSearch is a data class containing a search response. You can see in this particular case that both have the same external API, but a different internal implementation. In the Swift case we are using Unbox for JSON mapping, while in Kotlin we use Jackson. Here we can see the first issue that was commented above: library differences. The good news are that it is an implementation detail that will not affect how you use the object at all, and that you could probably find (or build) a different mapping library that looks in the same way (or at least much more similar) in both platforms.

RestaurantService is a class that provides access to the OpenTable API. It provides a couple of methods to make search queries, and return a ServiceTask object that encapsulates the networking request and mapping. The resulting code as you can see is almost identical, except for the usage of a UrlSession vs a VolleySession and minor syntactic differences. Of course, once again the implementation details of the NetworkRequestServiceTask will be different in both platforms to deal with the networking libraries, but API wise they are the same and the NetworkRequestServiceTask and its dependencies can be reused across projects.

Here he have RestaurantListState, which is just a plain class holding state information used by the ViewModel. In this particular case, there are no dependencies to any other library or system framework, and therefore the code is again very similar except for the minor differences commented above (ex: static methods vs companion methods or struct vs data class)

This class corresponds to the ViewModel that will be used by the list of restaurants screen. As you can see, once again code fully resembles to each other, with the small difference of memory management and guard statement in the Swift case. Very interesting to note as well is that this is the first code snippet using Rx. You can see how they both share the same methods and objects, so the resulting code is equivalent in both platforms. Thanks Rx for keeping consistency!

RestaurantsCoordinator is the class responsible of navigation and coordination between the different parts in the MVVM. It basically instantiates new views, view models and services when needed, and present them in screen. Check it out because even if the navigation in both platforms is handled differently, the resulting code is so similar that you can barely notice the differences except for the constructors and statics.

OK, so here is the big deal. So far, code was very similar and can be easily shared (with small editions) from one to the other platform. However, as we warned above, the UI code will be very different. How much? You can compare it by yourself…

Basically, they both share a common approach in which they have a constructor receiving the dependencies (for a very simple Dependency Injection); a view creation method (viewDidLoad / onCreate) that basically subscribes to the ViewModel observables and configures the list; a view appear method (viewWillAppear / onResume) that will load new results; and a set of methods and types to deal with the information from the list, which by the way could have been moved partially to the ViewModel probably.

As you can see, they are similar (especially conceptually) but not equal, so all in all I would say that you could use one as a template for the other, but you will still need to write about half of the code, but judge it yourself.

Of course, if you create your own wrappers around the UI components, you could actually achieve a much higher code reuse rate by exposing similar APIs, but you will need to develop them and they will introduce extra learning steps for new developers (like I did for networking in the NetworkServiceTask, use a similar API with different implementations)

Off-topic: note how the usage of Kotlin extensions removed all of the findViewById so typical (and error prone) in Android UI classes, and in iOS the usage of R.swift is also cleaning up many of the hardcoded strings.

Layout

In this case I am not copying the layout code because it is completely different. In iOS, I have used Interface Builder to set my views, while in Android it uses layout XMLs.

Conclusion

Swift and Kotlin are great languages, both adding a lot of added value to their corresponding alternative for mobile apps (Objective-C / Java). They are safer thanks to a strict strongly typed system that includes nullability in it. They are both very pleasant to work with because of a impressive type inference compiler and a beautiful and modern syntax. They both have very powerful features, like extensions, immutability and functional programming additions that allow new and better patterns and constructions to emerge.

However, although very similar, they are not identical. They have a few differences intrinsic to the language and the SO/runtime where they run that makes impossible to use the exact same code in both platforms. Nevertheless, if we structure our code with a good pattern and separation of concerns, we can certainly get very similar code in most of our classes, keeping the main differences when interacting with system APIs like UI or Networking isolated.

We have seen a few examples of different parts of the app using MVVM + Rx + Coordinators, and we can see how code resembles to each other in the example classes (between 50% to 90% code matching, not counting layout). In fact, it is so similar that I made most of one platform as a copy+paste+edit from the other one, saving a lot of time and reducing bugs as both will behave almost identically. An added benefit is that Kotlin developers will be able to read/write Swift with ease and vice versa, which helps consolidating teams, practices and code across platforms, but still writing fully native and high quality apps with small differences to adapt to different user’s expectations derived from the platform itself (which is a big difference with other cross platform solutions out there like ReactNative, Xamarin or PhoneGap/Cordova)