See How Kotlin vs Swift Realign and Refurbish Mobile App Development!

blog_img
Swift aims to attain its main goal of total world domination by the end of 2019. It forgot about Kotlin, but later remembers that! Watch the debate between Kotlin vs Swift!

Excellent tool support and interoperability with Java, Objective C and now Swift act as invaluable hacks for Kotlin programmers. Google’s support and availability of Android Studio for Kotlin have further counterbalanced app development across platforms. This excerpt discusses various features required to leverage Swift knowledge to learn Kotlin, highlighting the similarities and differences between both programming languages. Get a load of Swift code examples and simultaneously walk through towards coding Kotlin equivalents providing an opportunity for developers to get hands-on-experience using their iOS knowledge to construct an Android UI.

Along with some of the parallels like easy syntax, interoperability across platforms, the inheritance of object-oriented features, regular upgrades and less coding; there are some differences between the two languages in a context that drove them apart.

Enumerating the basic features of Swift and Kotlin:

Essential Features in Swift

  • Enumerations are strong point.
  • Data classes are absent.
  • No delegated classes or delegated properties.
  • Absence of annotations.

Essential Features in Kotlin

  • Classes in Kotlin are final by default.
  • Struct or passing by value are absent.
  • Absence of tuples.
  • No typealias.
  • Guard statements are absent.

The quickness with which both languages gained adoption has helped increase the number of developers for both platforms. Swift was initially developed to work with Cocoa Touch Framework, can be mixed with Objective C in projects but is meant to replace it. Kotlin was designed to seemingly interoperate with Java and to make object-oriented features more functional.

Understanding the Similar Points in Kotlin and Swift

Let’s share the similarities, and celebrate the differences in Swift and Kotlin in subsequent discussion. Although Swift is a native iOS app development platform, Kotlin can be used for cross-platform app development. With minor adjustments their syntax looks and behaves in same way:

Similarities

Swift

Kotlin

Declaring Properties
Mutable as well as immutable properties can be declared with ease in both Swift as well as Kotlin.
var age: Int = 09

var firstName = “Kon”

var age: Int = 09

var firstName = “Kon”

Data Structures
Arrays can be mutable, are collection of strings but not a mixture of strings and integers. But these are declared with fixed size.
var names = Array<String>()

To append values:
names.append(“Fuad”) //index 0
names.append(“Eric”) //index 1
names.append(“Joe”) // index 2

To declare immutable array:
let days = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”]

val numbers = Array<Int>(5){0}numbers[1] = 2 //numbers is now (0, 2, 0, 0, 0)

Immutable array:
val days = arrayOf(“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”)

Lists in Kotlin are similar to Swift’s array type:

var names = ArrayList<String>() //creates a list of strings, initially with no elements

Adding Values:
names.add(“Neil”) //index 0
names.add(“Joe “) //index 1
names.add(“Eric”) // index 2

Declaring an Immutable List:

val days = listOf(“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”)

Swift’s Dictionary and Kotlin’s Map are very useful data structures for storing values.Creating a Swift Dictionary:
var namesWithAges : [String: Int] = [:]
namesWithAges.reserveCapacity(20) //define capacityAssigning Values:
namesWithAges[“John Doe”] = 34Declaring Immutable Dictionary:
let namesWithAges = [“John Doe” : 34, “Jane Doe” : 29]
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

While creating immutable map:

val namesWithAges = mapOf(“John Doe” to 34, “Jane Doe” to 29)

High Order Functions

These make the code readable and maintainable as these operate on other functions by either taking functions as argument or returning a function.

Prototype of Swift Function:

func functionName(parameterName: DataType) -> ReturnType {
//function body
}

An example of Swift Function:
func getGreetings(name: String) -> String {
return “Hello \(name)!”
}

Swift default argument:
func getGreetings(name: String = “World”) -> String {
return “Hello \(name)!”
}

Prototype of Kotlin Function:
(1)
fun functionName(parameterName: DataType): ReturnType {
//function body
}
(2) Taking Function as Parameter/argument:

fun passMeFunction(abc: () -> Unit) {
// I can take function
// do something here
// execute the function
abc()
}
(3) Can return a function:

passMeFunction(
{
val user = User()
user.name = “PQR”println(“FUNCTIONS ARE EASY”
}
)An example of Kotlin function:
fun greetUser(name: String): String {
return “Hello ${name}!”
}Kotlin default argument:
fun greetUser(name: String = “World”): String {
return “Hello ${name}!”
}
Lambda in Kotlin vs. Closure in Swift are useful building blocks in coding arena.Closures in Swift:
var square = { (a: Int) -> Int in
return a * a
}
print(square(4))Taking a cue from above example, in which the type of the variable square has already been established as an integer, the closure can be re-written as:
square = { //we can even omit the parameter list
$0 * $0
}
print(square(3)) //9
Using a Lambda in Kotlin:

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

Calling a lambda by placeholder object name it for the parameter:
var multiple: (Int) -> Int = { it * it }
println(multiple(4)) //16
multiple = {it * it * it} //don’t need ‘->’
println(multiple(2)) //8

Currying functions enable Lambda calculus, and permits to reduce the function to less complex ones which may already exist in your SDK and help reduce the code.

Nullable types and Kotlin vs. Optional types in Swift
Both Kotlin and Swift languages are “Safe” and cannot have Null/Nill values (by accident).In both these languages such types are represented by a question mark “?” placed to the right of the variable type.
Optional Type in Swift:

var authToken: String? = “a long string”

authToken = nil

Nullable Type in Kotlin:

var authToken: String? = “some long string”

authToken = null

Null Safety

  •  This is important to avoid the crashes when a null value is accessed.
  • Both languages provide specific syntax for properly unwrapping nullable types.
  • It is not recommended to “force unwrap” an optional type in Swift (or to use a not-null assertion for Kotlin’s nullable type) Force unwrapping can be done by making use of an exclamation sign “!” in Swift and “!!” in Kotlin.
Swift’s “Nil-coalescing operator” (introduced in Swift 3) works in the same way as Elvis operator in Kotlin.

let id: Int? = nil
var userId = id ?? -1 //prints -1

Besides, “if let” expression is also a proper method to handle optionals:

let id: Int? = nil
if let userId = id {
print(userId)
} else {
print(“userId is nil”)
}

Null Safety in Kotlin:

var id: Int? = 15
var userId = 0
if (id != null) {
userId = id
} else {
userID = -1
}
println(userID) //prints 10

Kotlin also makes use of Elvis operator to make above situation consice:

var id: Int? = null

val userId = id ?: -1 //userID is -1

Elvis operator does not let Android developers feel the absence of Guard statement in Kotlin.

Elvis operator can also be used with safe cast:

fun readyForParade (participant : Bandmember) : Boolean {
val trombonePlayer = participant as?  Bandmember ?: return false
return trombonePlayer. practiceTime > 6000
}

“If Let” expression in Swift vs. “Smart Casts” in KotlinIn Kotlin as the nullable cast gets its correct type or becomes not null, the cast variable can be used directly for rest of scope of program:

val id: Int? = null
if (id != null) {
print(id) // id can be used directly in this scope
} else {
print(“id is null”)
}

Control Flow  -“if-else” statementsSwift adopts parentheses, although the basic if-else statement remains same:

if a > b {
print(“Choose a”)
} else {
print(“Choose b”)
}

If-else statement in Kotlin is similar to the syntax in most other languages:

if (a > b) {
println(“Choose a”)
} else {
println(“Choose b”)
}

Switch” StatementSwift makes use of “Switch” as follows:
let x = 3
switch x {
case 1:
print(“x == 1”)
case 2:
print(“x == 2”)
default:
print(“x is neither 1 nor 2”)
}
“Switch” = “When” in Kotlin.

val x = 3
when (x) {
1 -> println(“x == 1”)
2 -> println(“x == 2”)
else -> {
print(“x is neither 1 nor 2”)
}
}

For” LoopFor loop in Swift: 

let days = [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”]
for day in days {
print(day)
}

Range operator in Swift differs slightly in Swift: 

for item in 1..<10 {
print(item)
}

Loops in Kotlin:

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

For Loop by making use of “range operator”: 

for (item in 1..10) {
println(item)
}

Declaring a class – is almost same in Kotlin and SwiftExample of class declaration in Swift:

class ViewController: UIViewController {

}

Example of class declaration in Kotlin:

class MainActivity: AppCompatActivity() {

}

Constructor in Kotlin vs. Initializer in Swift Example of Initializer in Swift:

public class Car {
let model: String

init(model: String) {
self.model = model
}
}

Example of Constructor in Kotlin:

class Car constructor(_model: String) {
val model: String

init {
model = _model
}
}

Extensions – help in extending the existing features of a class.“Int” class with a functions that returns square of an integer can be extended in Swift as:

extension Int {
func square() -> Int {
return self * self
}
}

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

“Int” class with a functions that returns square of an integer can be extended in Kotlin as:

fun Int.square(): Int {
return this * this
}

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

Interface in Kotlin vs. Protocol in SwiftRepresentation of Protocol:
protocol Animal {
var canFly: Bool {get}func eat()func makeSound()
}
Representation of Interface:
interface Animal {
var canFly: Booleanfun eat()fun makeSound()
}
Default Implementationprotocol Animal {
var canFly: Bool {get}
}extension Animal {
var canFly: Bool {
return false
}
}
interface Animal {
val canFly: Booleanget() = true
}
Functional Programming ToolscompactMap, map, filterfilterNotNull, map, filter

Figure Out the Differences: Kotlin vs Swift?

Dissimilarities

Swift

Kotlin

“Data Class” in Kotlin vs. “Struct” in SwiftExample of Struct declaration in Swift:

struct Person {
let name: String
let dob: String
}

let personOne = Person(name: “Jon”, dob: “12 August”)
var personTwo = personOne // assign to another variable
personTwo.name = “Vanessa”
print(personOne.name) // prints Jon
print(personTwo.name) // prints Vanessa

Example of Data Class declaration in Kotlin:

val personOne = Person(“ALI”, “11 November”)
val personTwo = personOne // assign to another variable

personTwo.name = “Vanessa”
println(personOne.name) // prints Vanessa
println(personTwo.name) // prints Vanessa

“Val” in Kotlin vs. “Let” in SwiftExample of “Let” in Swift: 

let persons = [Person(name: “Jonathan”, dob: “12 Sept”),
Person(name: “Kimono”, dob: “20 July”),
Person(name: “Venu”, dob: “10 August”),
Person(name: “Alena”, dob: “27 Feb”)]
persons.append(Person(name: “Shaun”, dob: “11 Jan”)) // throws compile time error

Example of “Val” in Kotlin: 

val persons = mutableListOf(Person(“Jon”, “12 August”),
Person(“Kim”, “10 July”),
Person(“Vanessa”, “12 August”),
Person(“Alisa”, “26 March”))
persons.add(Person(“Shaun”, “11 Jan”)) // can append a new value

Follow the Footprint: Kotlin vs Swift

Both Kotlin and Swift can be used to develop across platforms, share many features, are highly performant, are used for server-side development, treat declaration of properties, data structures, functions in a similar way; they require programmers to declare variables, classes, and control flow (if-else, for-loop) properly.

While constructor, immutable variables, mutable variables, self-object referencing, arrays, dictionaries/maps, type inference, function declaration, function default parameters, If statements, For loops, Default values, Safe casting, Safe call, Force unwrap, lazy initialization are major points of differences. (Few of these are discussed above)

Frameworks that ease Swift coding include ABI stability, SwiftNIO HTTP2 support, Vapor 4, Swift Package Manager & Xcode, Marzipan – Phase 2, Kitura and theswiftdev.com. Use of Android Studio 3.0 as IDE with fully tested Kotlin support enables developers to make extensive use of Kotlin at website backend. Moreover, it also chalks out the heavy use of kotlin at backend of services for the platforms (OS) the developers are trying to target. While JVM is the most common, Android closely follows it. Spring Boot, Kotlin-Native, Scade, Kotlinx.coroutine, Kotlin.test, Ktor, Anko Commons, Kotlinx.html, Exposed, Anko Coroutines, Anko Layouts, Kotlinx.dom, etc are the most prevalent frameworks that ease creating a mobile app in Kotlin. Quell any signs of dissent, by talking to our experts on Kotlin and Swift app development.

YOU MAY ALSO LIKE
About Author
Neeti Kotia

Neeti Kotia

Neeti Kotia is a technology journalist who seeks to analyze the advancements and developments in technology that affect our everyday lives. Her articles primarily focus upon the business, social, cultural, and entertainment side of the technology sector.

MAKE YOUR IDEA REACH ITS GRAND DESTINY

WITH PRO WEB AND MOBILE SOLUTIONS

Looking for a development partner?

Portfolio

Visit Our Portfolio

Top Mobile Blog Winner

Top 15 Latest Mobile Blogs

Mobile App Blog Winner

Mobile App Blogs

SUBSCRIBE TO OUR BLOG

Top

Get a perfect quote

We’re eager to work with you. Please share your project goals and contact information. We respond to 97% of messages within 1-2 business day. Really!

Or send us an email at: [email protected]