Logo for tanaschita.com

Introduction to Kotlin for Swift developers - variables, functions & control flow

Learn the main concepts of Kotlin from a Swift developer's point of view.

15 Aug 2023 · 6 min read

If you are a iOS developer learning Kotlin - which is the main programming language for Android development - or you just want to take a glimpse into another modern programming language, this article series may be for you.

This is a 4-part article series which will cover the following Kotlin topics from a Swift developer's point of view:

  1. In part 1 (this article), we'll look into basic concepts like variables, functions and control flow.
  2. In part 2, we'll take a closer look into classes, structs and enums.
  3. In part 3, we'll look into protocols, extensions and generics. (coming soon)
  4. In part 4, we'll look into asynchronous programming. (coming soon)

Let's get started.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Variables & Optionals

The syntax between Swift and Kotlin is quite similar. As a Swift developer, you most likely will be able to read Kotlin code and understand most of it right from the beginning, and also recognize a lot of features you know from Swift.

Let's look at the following code:

Kotlin

fun sumOf(x: Int, y: Int? = null): Int {
println("x is $x, y is $y")
if (y != null) {
val result = x + y
return result
}
return x
}

Swift

func sumOf(x: Int, y: Int? = nil) -> Int {
print("x is \(x), y is \(y)")
if let y {
let result = x + y
return result
}
return x
}

As we can see above, the Kotlin code is almost self-explanatory since the syntax in both languages is only slightly different. A few things to point out:

  1. To define constants, Kotlin provides the val keyword (equivalent to let in Swift).
  2. For mutable variables, it even has the same keyword as Swift: var result = ....
  3. Just like Swift, Kotlin supports type inference. The type of the result variable is inferred, we don't need to explicitly specify it with val result: Int = x + y.
  4. Just like Swift, Kotlin supports optionals. While we use a if let binding in Swift to unwrap optionals, in Kotlin, an optional variable is automatically casted to non-nullable after a null check.

Similar to Swift, Kotlin also supports optional chaining and forced unwrapping:

result?.user?.isValidated // optional chaining in Kotlin
result!!.user!!.isValidated // forced unwrapping in Kotlin

Functions

In the example above, we already saw a function in action:

fun sumOf(x: Int, y: Int? = null): Int {
...
}

Similar to Swift, functions in Kotlin support default arguments. Kotlin provides a lot of flexibility for calling functions. We can call the function without the argument names or by using named arguments. When using named arguments, we can freely change the order that they are listed in.

Here are valid possibilities we can call the above function in Kotlin:

sumOf(1)
sumOf(x = 1)
sumOf(1, 4)
sumOf(y = 4, x = 1)

Similar to Swift, Kotlin functions are first-class which means they can be stored in variables and can be passed as arguments to and returned from other functions. A function type in Kotlin is defined as follows:

(Int) -> String

Which is the same syntax as in Swift. Kotlin also provides similar higher-order functions like map, filter, reduce and more:

Kotlin

val numbers = intArrayOf(1, 2, 3)
val numbersTimesTwo = numbers.map { it * 2 }
val sum: Int = numbers.reduce { acc, next -> acc + next }

The equivalent in Swift looks as follows:

Swift

let numbers = [1, 2, 3]
let numbersTimesTwo = numbers.map { $0 * 2 }
let sum = numbers.reduce(0) { $0 + $1 }

In Kotlin, the implicit parameter name it can only be used for single parameters.

Control flow

Kotlin provides similar control flow statements we already know from Swift. An if-else-statement was already shown in previous examples. Let's look at two other often used statements - the when statement and the for-loop.

when defines a conditional expression with multiple branches.

Kotlin

enum class Color {
RED, GREEN, BLUE, BROWN
}
when (color) {
Color.RED -> println("red")
Color.GREEN, Color.BLUE -> println("green or blue")
else -> println("otherwise")
}

As we can see above, it is very similar to the switch statement in Swift. Just like in Swift, the else statement is not required when all possible cases are covered. The Swift equivalent looks as follows:

Swift

enum Color {
case red, green, blue, brown
}
switch self {
case .red:
print("red")
case .green, .blue:
print("green or blue")
default:
print("otherwise")
}

For loops in Kotlin are also very similar to those in Swift:

Kotlin

for (item in items) {
// ...
}

The only difference are the parentheses which we can leave out in Swift:

Swift

for item in items {
// ...
}
Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

beyond ios

swift

ios

Introduction to Kotlin for Swift developers - classes, structs & enums

Learn how classes, structs and enums work in Kotlin from a Swift developer's point of view.

25 Sep 2023 · 8 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum