Photo by Samuel Zeller on Unsplash

In this new series of short articles, we will compare both Kotlin and Swift, paying attention to constructs, syntax and semantics.

As usual, we begin at the beginning: declaring variables and constants.

In Kotlin

We use the reserved keywords “var” and “val” to declare variables and constants respectively:

var attempts = 0
val maxAttempts = 3

In Swift

The declaration is very similar: we keep the “var” keyword for variables, but use “let” (instead of val) for read-only values:

var attemps = 0
let maxAttempts = 3

Keyword “let” is also used when unwrapping an optional using the if-let construct. As we will see when we talk about optionals, this construct allows to:

  • safely check if some variable has a valid value or not
  • if having a valid value, extract it and store it on another data structure
if let <<some_constant_name>> = <<some_variable_name>> {
   //TODO: retrieve value is valid, so use it here to perform some operation...
}

Common properties

In both languages constants provide us immutable objects that only can be assigned once, so:

  • we cannot reassign its value
  • we cannot modify the referenced object either

Some code like the following will get the compiler complaining:

val welcomeMsg = "Hello world"
var farewellMsg = "Good bye"

// Error...
welcomeMsg = farewellMsg

Finally, both languages are statically typed, so we have to specify data type in declarations:

var attempts : Int = 0

However, most of the times this is not needed, because compiler applies type inference from the value assigned to the variable. It’s only necessary if we declare a variable/constant but we do not assign its value right away.

Wrapping up…

Declaration and semantics for variables and constants are almost identical in both languages, being applied keywords the only difference to keep in mind. Type inference allow us to omit data type when declaring structures.

You can find some code to play with in the following link:

https://pl.kotl.in/_Zjzpb0yw

Join the Conversation

1 Comment

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: