BLOG
21 November 2022

Kotlin vs Swift - How do They Compare? Part One.

tech

According to the latest stackoverflow survey Swift and Kotlin are among the most-loved programming languages. Both are becoming more and more popular and have almost completely replaced the venerable Java and Objective C in the world of mobile platforms. It’s not a surprise, as the giants of the IT industry such as Apple, JetBrains and Google are involved in their development. If you are an Android or iOS developer, you likely know at least one of these languages.

This article summarizes the most significant syntax differences between the languages. Knowing them allows you to switch to a second language and become a Swifter if you are a Kotliner, and vice versa. The article will not, however, explain differences in memory management or between iOS and Android platforms.
 

At the time of writing, Swift is in version 5.7 and Kotlin version is 1.7.20. 
Some code snippets are incomplete or lack input validation for the sake of simplicity.
 
Ok, lets get started.

Keywords


The majority of the keywords are interchangeable and have the same meaning. For example, 'if', 'else', 'for', 'while', and 'continue' statements work in the same way as they do in other C-like languages.
 
Part of the reason for keyword differences is that the applications written in the languages use different memory models. Swift keywords like 'weak' and 'unowned' aid in resolving retain cycles, which Kotlin programmes do not have.

Access level (visiblity modifiers)

Both languages support access levels such as 'public,' 'internal,' and 'private.' The underlying meaning is the same. Swift supports the 'fileprivate' access level but not the 'protected' access level.

Functions

Kotlin functions are declared using the ‘fun’ keyword whereas Swift functions are declared using the ‘func’ keyword. To declare a return type, Kotlin uses colon (:) notation, Swift arrow (->). 

If a function does not return any value, the return notation along with the type declaration can be omitted. Both languages support named arguments and default arguments values.

Labels make using functions in Swift more natural.

If you don’t want an argument label for a parameter, type an underscore '_'  instead of an explicit argument label for that parameter.

Static methods

In Kotlin class methods are created inside the 'companion object' block. There is no the 'static' keyword in Kotlin.

Swift takes a bit more conservative approach. The 'static' and 'class' keywords are used to utilize class functionality without creating an instance. Subclasses can override 'class' methods but they can not override 'static' methods.

Static variables

In Kotlin, a class variable, just like a class function, has to be declared inside 'companion object' block.

To declare a class variable in Swift, declare it as a normal variable, prefixed with the 'static' keyword.

Parentheses

Usage of parentheses for contional statements, loops, 'guard', 'switch' is not required in Swift language. In Swift, parentheses are considered redundant, causing unnecessary syntactic noise. Linters (such as SwiftLint) will warn you if you include redundant parentheses.

Inline if

There is no ternary operator in Kotlin. Really. Fortunately, 'if' is an expression: it returns a value. Hence, the way Kotlin declares an inline if is also expressive

Swift supports ternary operator like most languages do.

String interpolation

In Kotlin, use the dollar sign ($) before a variable name to interpolate a value of this variable into a string.

In Swift wrap the variable in a pair of parentheses, prefixed by a backslash.

 

Mutability

In Kotlin, mutability means that a 'var' variable can be reassigned  with another value. Variables declared with the 'val' keyword are immutable and can not be reassigned.

In Kotlin, if a class variable is declared with the 'var' keyword, we can reassign it, even if an instance of the class is declared immutable.

Kotlin distinguishes mutable and immutable collection classes. Mutable collections allow adding and removing items, immutable collections are fixed-size.

In Swift, an immutable variable cannot be reassigned, and the variable value can not be changed. 

Declare mutable variables with the 'var' keyword and immutable with the 'let' keyword.

Loops

Both languages support  'for' and 'while' loops. The 'do' keyword in Swift is reserved for beginning of an exception-handling block, so the following loop construct:

is not supported in Swift, but you can use the `repeat` instead:

 

Error handling

In Kotlin, errors are represented by instances of classes that extends the 'Throwable' class. Kotlin does not have checked exceptions, functions are not denoted with the 'throws' keyword. The well known 'try/catch/finally'  block is the way to handle exceptions.

In Swift, errors are represented by values of types that conform to the Error protocol. If a function calls other throwing function, the calling function has to catch an error or rethrow it. Throwing functions are marked with the 'throws' keyword. Swift does not have the 'finally' block. You can run cleanup actions using the defer statement.

Flow control with 'switch' statement

Kotlin does not have the traditional 'switch-case' statement. Kotlin has the 'when' statement.

Swift’s switch statement is more powerful than its counterpart in many C-like languages.

Null safety

Both languages support nullable types AKA optionals. Declaration of an optional variable is identical for Kotlin and Swift.

However, there are minor differences for using optionals. Check the examples below to understand how to use optionals in the languages.

Forced optional unwrapping

Null/nil fallback

Kotlin has the ??: operator, known as Elvis operator.

Swift has ?? nil coalescing operator.

Unwrapping with conditions

Kotlin has a cool feature called smart cast. When an immutable optional is verified as non null, it becomes a non nullable variable.

Swift:

Checking pre-conditions with guard clauses

Both languages offer one-liner statements used to validate input against null variables.  
In Kotlin, use Elvis operator.

In Swift, guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

Lambdas

Both languages support higher-order functions and lambda statements. There are minor differences between the languages especially in naming implicit variables. Let's look into the examples.

Ranges

Kotlin has closed ranges:

Ranges in Swift are more advanced:

This is everything for now, but in the second part of the article we will take a closer look at the differences between abstractions, classes and inheritance. I hope you find the article useful and will come back for part two!


Author
Robert Andrzejczyk
iOS Developer