A Comparison of Swift and Kotlin Languages
This article focuses on the main similarities and differences between Swift and Kotlin, including implementation, style, syntax and other important details. By Aaqib Hussain.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
A Comparison of Swift and Kotlin Languages
30 mins
- Understanding Similarities Between Swift and Kotlin
- Declaring Properties
- Kotlin — Mutable Properties
- Swift – Mutable Properties
- Kotlin — Immutable Properties
- Swift — Immutable Properties
- Data Structures
- Arrays
- Dictionaries / Maps
- Functions
- Lambda Functions / Closures
- Nullable / Optional Types
- Handling a Nullable / Optional Type
- Control Flow
- Classes
- Class Extensions
- Interface / Protocol
- Functional Programming Tools
- Understanding Differences Between Swift and Kotlin
- Where to Go From Here?
Swift and Kotlin have taken the developer community by storm, helping to increase the number of developers for both platforms. Both languages rapidly gained adoption due to their easy syntax, simple way of writing and the modern techniques and features they bring to the table.
Swift first appeared in June 2, 2014, and was developed by Apple to work with the Cocoa Touch framework. It works on top of the LLVM, an open source collection of compilers and toolchains. Swift has been a part of Xcode since version 6 was released. Apple open sourced Swift on December 3, 2015. Swift can be mixed with Objective-C in projects, but is meant to replace Objective-C.
Initially, Kotlin was developed by a group of developers from Saint Petersburg, Russia, working at the company JetBrains. Kotlin was publicly unveiled in 2011. Kotlin runs on the JVM and is designed to interoperate seamlessly with Java, and is meant as a replacement for Java. Google announced official support for Kotlin as a development language for Android in 2017. Kotlin rolled out with Android Studio 3.0 in October 2017.
In this article, you will take a tour of Swift and Kotlin and how they compare. While there is no hands-on tutorial, reviewing these language elements will provide you a great overview that will expand your knowledge of both of these languages. This tutorial assumes you have a basic understanding of either Swift or Kotlin.
Understanding Similarities Between Swift and Kotlin
Swift and Kotlin are incredibly similar to one another. If you’d like to try out any of the following code snippets below for yourself, you can do so using a web playground for Kotlin or an Xcode playground for Swift.
Declaring Properties
In both languages, there is a concept of mutability and immutability. Mutable properties can be changed or re-assigned but immutable properties can’t change.
Declaring an integer in Kotlin:
var age: Int = 15
To declare a property with type inference:
var firstName = "Ray"
Declaring an integer in Swift:
var age: Int = 15
To declare a property with type inference:
var firstName = "Ray"
val hoursInADay = 24
val secondsInAMinute = 60
val quote = "If you don't work smart, you will probably be replaced by an AI."
let hoursInADay = 24
let secondsInAMinute = 60
let quote = "If you don't work smart, you will probably be replaced by an AI."
So, as you can see above, the basic difference between declaring immutable properties in Kotlin and Swift are the val
and let
keywords.
Data Structures
Data structures are an important part of any language. They are used to organize, store, and manipulate data. Arrays, linked lists, dictionaries or maps, classes and interfaces are all examples of data structures.
In both Swift and Kotlin, arrays have a fixed type — i.e., an array could be a collection of strings, for example, but not a mixture of strings and integers.
Swift — Array
Declaring a mutable array in Swift:
var names = Array<String>()
To append values:
names.append("Fuad") //index 0
names.append("Eric") //index 1
names.append("Joe") // index 2
Declaring an immutable array in Swift:
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
Kotlin — Arrays and Lists
In Kotlin, arrays can be mutable, but are declared with a fixed size. In the following example we declare a mutable array in Kotlin with five elements, all set to a default value of zero:
val numbers = Array<Int>(5){0}
To change the value of an item in the array:
numbers[1] = 2 //numbers is now (0, 2, 0, 0, 0)
Note that, while the array above is mutable, you were able to assign it to a immutable variable using the val
keyword – more on this later.
Declaring an immutable array in Kotlin:
val days = arrayOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
Another Kotlin collection type, lists are similar to Swift’s array type. Lists can have a variable number of elements and can grow in size after declaration.
var names = ArrayList<String>() //creates a list of strings, initially with no elements
To add values to a Kotlin list:
names.add("Fuad") //index 0
names.add("Eric") //index 1
names.add("Joe") // index 2
Declaring an immutable list in Kotlin:
val days = listOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
A dictionary (Swift) or map (Kotlin) is a very useful data structure when it comes to storing distinct values. While dictionaries and maps by default can expand, in both Kotlin and Swift, you can define their capacity for improved performance.
Kotlin
var namesWithAges = HashMap<String, Int>()
var namesWithAges = HashMap<String, Int>(20) //define capacity
Assigning values:
namesWithAges.put("John Doe", 34)
//OR
namesWithAges["John Doe"] = 34
Creating an immutable map:
val namesWithAges = mapOf("John Doe" to 34, "Jane Doe" to 29)
Swift
Creating a Swift dictionary:
var namesWithAges : [String: Int] = [:]
namesWithAges.reserveCapacity(20) //define capacity
Assigning values:
namesWithAges["John Doe"] = 34
Declaring an immutable dictionary:
let namesWithAges = ["John Doe" : 34, "Jane Doe" : 29]
Functions
Functions are the essential building blocks of any codebase. They help organize the code in a manner that makes it readable and maintainable.
Kotlin Functions
Prototype of a Kotlin function:
fun functionName(parameterName: DataType): ReturnType {
//function body
}
The return type of a function is represented by a colon :
. In Kotlin, all functions have a return type; if you don’t specify the return type, a special type Unit
will be returned by default.
Here’s an example of a Kotlin function:
fun greetUser(name: String): String {
return "Hello ${name}!"
}
Kotlin — Default Argument
In Kotlin, a default value can be assigned to a parameter. For instance, take the example of the above function.
fun greetUser(name: String = "World"): String {
return "Hello ${name}!"
}
Now, the above function can be called without passing an argument like this:
greetUser() //returns Hello World!
Swift Functions
Prototype of a Swift function:
func functionName(parameterName: DataType) -> ReturnType {
//function body
}
The return type of a function is represented by a ->
. Additionally, the type of a function Swift infers when the function is not explicitly returning a value is a special type, Void
, which is an empty tuple, written as ()
.
Writing an actual function in Swift:
func getGreetings(name: String) -> String {
return "Hello \(name)!"
}
Swift — Default Argument
A Swift function with default argument:
func getGreetings(name: String = "World") -> String {
return "Hello \(name)!"
}
Calling the function with its default behavior like:
getGreetings() //returns Hello World!