Logo for tanaschita.com

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

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

In the first part of Kotlin for Swift developers, we looked at Kotlin variables, functions & control flow and how those are similar or different from Swift.

In this part, we'll do the same for classes, structs and enums.

Let's get started.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Classes

Classes in Kotlin and Swift share several similarities. Both represent reference types, support inheritance, interfaces and protocols, allow setting up initial values and behavior using constructors or initializers and more.

Let's look at an example of a Kotlin class:

Kotlin

class User(
val name: String,
val age: Int,
) {
val allowAccess: Int
get() = !this.isVerified
private var isVerified: Bool = false
init {
// Constructor parameters name and age are available here
}
}
val user = User("tanaschita", 34)

To a Swift developer, the constructor in Kotlin may seem a bit unusual. While in Swift, init parameters are defined as part of the init function, a Kotlin class constructor is defined as a part of the class header.

If some additional initialization code is needed, it can be defined in the init block where all constructor parameters are available.

The same code in Swift looks as follows:

Swift

class User {
private let name: String
private let age: Int
private var isVerified: Bool = false
var allowAccess: Int {
return !isVerified
}
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let user = User(name: "tanaschita", age: 34)

Structs

Additionally to classes, Swift offers structs for value types. For example:

struct Circle {
let radius: Int
}
let circle = Circle(radius: 5)
let anotherCircle = circle

Since structs are value types, anotherCircle is a copy of circle and not a reference to circle.

Kotlin's value types are not as integral to the language as Swift's value types. To get similar behaviour, Kotlin provides data classes, for example:

data class Circle(val radius: Int)

When defining a data class, Kotlin automatically generates a copy() function, which can be used to get similar behaviour as Swift's struct:

val circle = Circle(5)
val anotherCircle = circle.copy()

Enums

Kotlin and Swift both support enumerations, which are used to represent a set of related values. A simple enumaration in Kotlin is very similar to Swift:

Kotlin

enum class Weekday {
MONDAY, TUESDAY, WEDNESDAY ...
}

Swift

enum Weekday {
case monday, tuesday, wednesday ...
}

We can provide a constructor for Kotlin enums, which is similar to rawValues in Swift enums:

Kotlin

enum class Weekday(val short: String) {
MONDAY("mo"),
TUESDAY("tue"),
...
}

Swift

enum Weekday: String {
case monday = "mo"
case tuesday = "tue"
...
}

A powerful feature of enums in Swift is that we can associate each state with a value, even with different types. For example:

enum Result {
case success(String)
case error(Int)
}

We can't do that with Kotlin enums. To achieve similar behaviour, we can use Kotlin's sealed classes.

sealed class Result {
data class Success(val data: String) : Result()
data class Error(val errorCode: Int) : Result()
}
fun handleResult(result: Result) {
when (result) {
is Result.Success -> {
println("Success: ${result.data}")
}
is Result.Error -> {
println("Error: ${result.errorCode}")
}
}
}
Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

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 - protocols, extensions & generics

Learn how protocols, extensions and generics in Kotlin work from a Swift developer's point of view.

02 Dec 2023 · 8 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum