Home / Apple / A comparison of Swift and Kotlin Languages

A comparison of Swift and Kotlin Languages

Swift and Kotlin have taken the developer community by storm, which helps to increase the number of developers for both platforms. Both languages ​​quickly achieved adoption due to their simple syntax, simple typing 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 LLVM, an open source collection of compilers and toolbars. Swift has been part of Xcode since version 6 was released. Apple opened from Swift on December 3, 2015. Swift can be mixed with Objective-C in projects, but intended to replace Objective-C.

Basically, Kotlin was developed by a group of developers from Saint Petersburg, Russia, working on the company JetBrains. Kotlin was published in 201

1. Kotlin runs on JVM and is designed to work seamlessly with Java, and is intended as a replacement for Java. Google announced official support for Kotlin as the development language for Android in 2017. Kotlin rolled out with Android Studio 3.0 in October 2017.

In this article, you want to take a tour of Swift and Kotlin and how they compare. Although there is no practical training, review of these language elements will give you a great overview that will expand your knowledge of both of these languages. This tutorial assumes that you have a basic understanding of either Swift or Kotlin.

Understanding Similarities between Swift and Kotlin

Swift and Kotlin are incredibly similar to each other. If you want to try out any of the following code snippets below for yourself, you can do it with a playground for Kotlin or an Xcode playground for Swift.

Declaring Properties

In both languages, there is a term about mutability and immutability. Reciprocal Properties may be changed or redistributed, but unchangeable properties can not be changed. [19659000] Kotlin – Mutable Properties

Declares an integer in Kotlin:

  was age 

  Declares an integer in Swift: 

  was age: Int = 15 

Explanation of a property with type preference:

  19659011] was firstName = "Ray" 

Swift - Mutable Properties

19659012] To declare a property with typewriter:

  was firstName = "Ray" 

Kotlin - Immutable Properties

  fall hoursInADay = 24
fall secondsInAMinute = 60
choice quote = "If you do not work smart, you will probably be replaced by an AI."

Swift - Immutable Properties

  la timerInADay = 24
let secondsInAMinute = 60
la quote = "If you do not work smart, you will probably be replaced by an AI."

So, as you can see, elections and are keywords.

Thus, you can see the basic difference between declaring unchangeable properties in Kotlin and Swift. Data Structures

Data structures are an important part of any language. They are used to organizing, storing and manipulating 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 - that is, a group can be a collection of strings, for example, but not a mixture of strings and integers.

Swift - Array

Declares a Reproductive Array in Swift:

 was Name = Array  ()

To add values:

 names.append ("Fuad") // index 0
names.append ("Eric") // index 1
names.append ("joe") // index 2

Declares an unchangeable selection in Swift:

 la days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

Kotlin - Arrays and Lists

In Kotlin, arrays can be mutable, but declare 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:

 selection numbers = Array  (5) {0}

To change the value of an element in the array:

 numbers [1] = 2 // numbers are now (0, 2, 0, 0, 0)

Note that while the array above is mutable you could assign it to an unchangeable variable using election the keyword - more on this later.

Declares an unchangeable selection in Kotlin:

 val days = arrayOf ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

Another Kotlin Collection Type, Lists is similar to Swift's array type. Lists can have a variable number of items and can grow in size after the declaration.

 var names = ArrayList  () // creates a list of strings, basically without elements

To add values ​​to a Kotlin list:

 names.add ("Fuad") // index 0
names.add ("Eric") // index 1
names.add ("joe") // index 2

Declares an unchangeable list in Kotlin:

 Val days = listOf ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

Dictionaries / Maps

A dictionary (Swift) or map (Kotlin) is a very useful data structure when it comes to saving different values. While dictionaries and maps can be expanded by default, both in Kotlin and Swift, you can define their capacity for enhanced performance.


 was namesWithAges = HashMap  ()
was namesWithAges = HashMap  (20) // defines capacity

Assign Values:

 namesWithAges.put ("John Doe", 34)
namesWithAges ["John Doe"] = 34

Create an Invariable Map:

 Select namesWithAges = mapOf ("John Doe" to 34, "Jane Doe" to 29)

Create a swift dictionary:

 was namesWithAges: [String: Int] = [:]
namesWithAges.reserveCapacity (20) // define capacity

Assign Values:

 namesWithAges ["John Doe"] = 34

Declare an Invariable Dictionary:

 la namesWithAges = ["John Doe" : 34, "Jane Doe" : 29]


Features are the basic building blocks of any codebase.

Kotlin Features

Prototype of a Kotlin Feature:

 Fun Feature Name (Parameter Name: DataType): ReturnType {
// function the body

The return type of a function is represented by a colon : . In Kotlin, all functions have a return type; If you do not specify return type, a special type Device returns as default.

Here is an example of a Kotlin feature:

 funny greetUser (name: String): String {
return "Hi $ {name}!"

Kotlin - Standard Argument

In Kotlin, a default value can be assigned to a parameter. For example, take the example of the above function.

 funny greetUser (name: String = "World"): String {
return "Hi $ {name}!"

Now the above function can be called without transferring an argument like this:

 greetUser () // returns Hello World!

Swift Features

Prototype of a Swift function:

 func function name (parameter name: DataType) -> ReturnType {
// function the body

The return type of a function is represented by a -> . In addition, the type of a function Swift infers when the function does not explicitly return a value is a special type, Void which is an empty tuple, written as () . [19659002] Write an actual feature in Swift:

 func getGreetings (name: String) -> String {
return "Hi  (name)!"

Swift - Standard Argument

A Swift function with default argument:

 func getGreetings (name: String = "World") -> String {
return "Hi  (name)!"

Calling the feature with default behavior like:

 getGreetings () // returns Hello World!

Lambda Features / Shutter

Lambdas (Kotlin) and Shocks (Swift) is another useful building block in your coding arsenal. Essentially, they are named functions. They can be assigned variables and transferred as any other value. The ability to process functions as values ​​is one of functional programming aspects of Swift and Kotlin. Some common occasions for closures include handling of asynchronous conversations, such as when you make a network request and work with collections.

Kotlin - Lambda

Using a lambda:

 val square = {a: Int ->
a * a
println (square (4)) // 16

The return type of a lambda is represented by a -> .

For lambdas with only one parameter, and whose type can be derived, Kotlin provides a placeholder object name that for the parameter, and -> can be eliminated, resulting in a more consistent syntax .

Calling a lambda using on :

 were more: (Int) -> Int = {it * it}
println (more (4)) // 16
more = {it * it * it} // do not need & # 39; -> & # 39;
println (more (2)) // 8

Swift - Closure

Using a Shutdown:

 was square = {(a: Int) -> Int in
return a * a
print (square (4))

In Swift is also the return type of a closure represented by a -> .

In the same way as Kotlin, this can be done more consistently using a placeholder object; However, in Swift, you are not limited to a single parameter. $ 0 is the placeholder object name Swift gives to the ending argument, where $ 0 $ 1 $ 2 etc. Is used for each successive parameter. If you continue from the example above, where the type of the variable square has already been created as an integer, you can rewrite your closure like this:

 square = {// we can even exclude the parameter list
$ 0 * $ 0
print (square (3)) // 9

Nullable / Optional Types

Both Kotlin and Swift are "safe" languages ​​that the values ​​can never be null / null by accident - the programmer must deliberately use a special type of variable that can either have a value or no value on a given time for an application cycle. In Swift these are called "optionals", and in Kotlin they are called "nullable". In both languages ​​are they represented by a ? located to the right of the variable type.

Kotlin - Nullable Type

 was authToken: String? = "a little long string"
authToken = null

Swift - Optional Type

 was authToken: String? = "a little long string"
authToken = null

The syntax for declaring null tables in Kotlin and optional in Swift is exactly the same.

Handling a null bar / optional type

To avoid crashes caused by trying to access zero value when not expected, both languages ​​have given specific syntax for the correct null null type. In both languages, it is not recommended to "force unpack" an optional type (or by using a null null claim for Kotlin's null load type unless you are 100% sure that the nullbar variable will always have a value Force unwrapping can be done using the exclamation mark ! in Swift and !! in Kotlin. Swift's ! Syntax serves as a warning in itself to the developer, and Kotlin takes it one step further! See what we did there ?:]

The following are some ways to properly handle an optional / nullable type.

Kotlin - Null Safety [19659032] where id: Int? = 10
was userId = 0
if (id! = null) {
userId = id
} other {
userID = -1
println (userID) // prints 10

In the above paragraph code, if id is equal to zero, userId will be assigned a value of -1.

In Kotlin is there even more concise way to utilize zero security via Elvis Operator ?:

 was id: Int? = null
choose userId = id ?: -1 // userID is -1

The Elvis operator ensures that you get a value out of the null amount no matter what by setting a default value if a null value occurs.

In the example above you use Elvis operator means userId will either be the value in id or -1 if id contains zero.

Both Swift and Kotlin support conditional casting (referred to as "safe cast" in Kotlin), although in Swift only applies to download to a subtype:


 was practiceTime = (trombone player as? band member) .practiceTime

Unlike Swift, in Kotlin, there is no guard statement. However, you can use the Elvis operator to similar effect.
Use what you learned earlier and combine the Elvis operator with a safe game like:

 funny readyForParade (participant: Band member): Boolean {
choose trombonePlayer = participant like? Bandmember ?: Return false
return trombone player. PracticeTime> 6000

Here, if the value of the safe rendered fails, readyForParade is zero and the function returns without further execution.

Kotlins let function when used in conjunction with Security Operator ?. provides a concise way to handle nullable expressions for.

 select userId = id.let {nonNullId -> nonNullId} ?: -1

Finally, Kotlin utilizes a feature called Smart Plugs that combines type controls and plugs. In Swift do you have if let the expression (see below) while in Kotlin have smart casts. Kotlin's smart casts seem a bit "smarter", while Swift is released a little more clearly when you read the code. Basically, in Kotlin, once a reset is proven to be true (it is not null or the type is correct type), for the rest of this range, the cast variable can be used directly without further rendering or additional syntax: [19659011] Val ID: Int? = null
if (id! = null) {
print (id) // id can be used directly in this scope
} other {
print ("id is null")

Conflict the above code with if let Swift sentence in the next section.

Swift – Optional Handling

Swift introduced Nil Coalescing Operator in Swift 3, which works more or less like Kotlins Elvis Operator.

 la id: Int? = null
was userId = id ?? -1 // prints -1

Swift uses whose let the syntax referred to earlier as the correct method of handling options, rather than forcing unopened:

 la id: Int? = null
if let userId = id {
print (userId)
} other {
print ("userId is null")

Swift uses guard the sentence to provide an early exit to code execution. It gives clarity to if you leave by checking for the condition you want instead of the one you do not and by keeping the bulk of your important code from being nested inside a if blockers.

Following a message some variables or constants were assigned values ​​using an optional binding as part of the state now available to approach the Kotlin's smart cast mechanism. for the rest of the code block such as the guard statement appears in. guard statement requires a condition other which breaks out of function.

 func registerUser (userId: Int?) {
guard la id = userId else {return}
// do things with id

Note that this is not exactly the same as Kotlins smart cast mechanism – in this example you could not have written userId.description as userId ] [19659007] Control Flow

Like features and closures, the building blocks of any app, if-else change for loops and other types of control flows are the logical glue that allows applications to work.

Kotlin – if-else

If-else works in Kotlin similar to most other languages:

 if (a> b) {
println ("select one")
} other {
println ("Select b")

Swift – if-else

A cool feature in Swift is that parentheses () around the condition are optional. I just wonder how long it will take for Kotlin to adopt this feature. ;]

 if a> b {
print ("select one")
} other {
print ("choose b")

Kotlin – when

when the name given to changed statements in Kotlin.

 val x = 3
when (x) {
1 -> println ("x == 1")
2 -> println ("x == 2")
otherwise -> {
print ("x is neither 1 or 2")

Swift switch

 la x = 3
change x {
case 1:
print ("x == 1")
case 2:
print ("x == 2")
print ("x is neither 1 or 2")

Note that in Swift, a breach statement must be exhaustive. In other words, a standard clause is required if each single possible value of the condition is not tested. This is not the case in Kotlin; so for swap statements Swift is actually clearer and less prone to programming errors. On the other hand, the syntax of changed sentences in Kotlin more consistently. In both languages, the sentence returns as soon as the first match state is evaluated, so there is no need for a pause statement.

Kotlin – for loop

There are a number of ways to write loops in Kotlin.

 val days = arrayOf ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
for (day in days) {
println (day)

for loop using the range operator:

 for (element of 1..10) {
println (mail)

In this example, .. specifies an inclusive area; The numbers 1 – 10 are printed. Both Kotlin and Swift provide a variety of different types of operators.

Swift – for loop

 la days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
for the day in days {
print (day)

Using another type of range operator, in Swift:

 for elements in 1 .. <10 {
print (post)


Declare one class in both languages ​​is almost the same:

Kotlin – Class

 Class MainActivity: AppCompatActivity () {


Swift – Class

 Class ViewController: UIViewController {


What are called "constructors" in Kotlin are "initiatives" in Swift. Kotlin also has a init block that is paired with a constructor.

Kotlin – Constructor

 class constructor (_model: string) {
Choice model: String

in the {
model = _model

Swift – Initializer

 Public Class Car {
Let Model: String

init (model: string) {
self.model = model

Class Extensions

Class extensions are a cool feature adopted by modern languages. It helps to extend the functionality of existing classes. Int Class with a function that returns a square of an integer:

 funny Int.square (): Int {19659000] 

Kotlin - Extension

return this * this } println (5.square ()) // prints 25

Swift – Extension

 extension Int {
func square () -> Int {
return yourself * yourself

print (5.square ()) // prints 25

Interface / Protocol

What is called an interface in Kotlin and other languages ​​is called a protocol in Swift. It helps you maintain a linked codebase, achieve polymorphism and write mocks for testing.

Kotlin Interface

In Kotlin, an interface declaration looks like a class statement:

 Animal Interface {
Var canFly: Boolean

fun eating ()

funny makeSound ()

Swift – Protocol

 Protocol Animal {
where canfly: bool {get}

func eat ()

func makeSound ()

An interface / protocol can also have a standard implementation. Standard behavior remains the same when it is called without overriding. Suppose you want the property canFly to be false under all circumstances to or unless it is necessary to change.

Kotlin – Standard Implementation

 Animal Interface {
Choice canFly: Boolean

get () = true

Swift – Standard Implementation

Extensions are used to provide protocols standard implementations:

 protocol Animal {
where canfly: bool {get}

expansion animal {
was kanfly: bool {
return false

Feature Programming Tools

These new languages ​​are packed with powerful tools that allow you to type code using a functional paradigm.


Map is used to transform data into a new form. There are many tools given by them, but just look at some of them.

Kotlin Map

Rate a data class Person, which contains property name and date of birth.

Data Class Person (Last Name: String, Dob: String)

Note : In Kotlin, a data class is similar to a class, but with the sole purpose of keeping data. This makes your code more consistent and you do not have to write an initialiser. Data classes are a powerful way in Kotlin to implement "value objects".

Now, consider a list that contains few items of the type Person:

 Select persons = listOf (Person ("Jon", "August 12"),
Person ("Kim", "July 10"),
Person ("Vanessa", "August 12"),
Person ("Alisa", "March 26"), null)

You may wonder why I assigned a null to the end of the list? There is no need to assign a list of null. Wait! You will get your reply soon enough. :]

Say that you want the names of all the people in their own list – this is where you want to use map the feature to help you.

choice name = persons.map {it? .name} // Jon, Kim, Vanessa, Alisa, null

Swift Map

Similarly, Swift considers a person struct :

 struct person {
leave the name: string
la dob: String

init (name: string, dob: string) {
self.name = name
self.dob = dob

And a number of people:

 let people = [Person(name: "Jon", dob: "12 August"),
  Person(name: "Kim", dob: "10 July"),
  Person(name: "Vanessa", dob: "12 August"),
  Person(name: "Alisa", dob: "26 March"), nil]

To transform the personal composition into a namespace:

 leave name = persons.map {$ 0? .name} // Jon, Kim, Vanessa, Alisa, null
   nil  objects from a group: 

Kotlin - filterNotNull

Source link