Nav Singh
2 min readDec 8, 2022

Swift vs Kotlin- Nullability

I recently began learning iOS development using Swift, and I have found that it is very similar to Kotlin.

Along the way, I learned about a concept called Optional, which is known in Kotlin as Nullable.

So let’s learn how Kotlin and Swift handle optional/nullable variables.

  • Swift has a concept called Optional, which means values can be absent (nil)
  • Kotlin has a concept called Nullable, which means that values can be absent (null)

Declaring optional/nullable

  • Swift
var name:String?
  • Kotlin
var name:String?

Let’s explore how optional/nullable can be handled in various ways

! Force unwrap !!

// Swift !
var name:String? = "Swift"
print("Name is \(name!)")
// Koltin !!
var name:String? = "Kotlin"
print("Name is: ${name!!}")

nil coalescing operator ?? Elvis operator ?:

// Swift ?? 
var name:String? = nil
print("Name is \(name ?? "Swift")")
// Koltin ?:
var name:String? = "Kotlin"
print("Name is: ${name ?: "Kotlin"}")

Check for nullable/optional using the if statement

// Swift if statement
var name:String? = nil

if name != nil {
// Swift is not smart enough here to inference the type of name.
// name is still optional here 🤯
print("Name is \(name ?? "Swift")")
}
// Koltin if statement
var name:String? = "Kotlin"

if(name != null){
// Kotlin is smart enough to infer the type of name here as String 😎
print("Name is: $name")
}

Optional binding(if let) and scope functions(let, also, etc.)

// Swift if let optional binding
var name:String? = nil

if let name = name{
// Here the type of name is String
print("Safe value received: \(name)")
}else{
print("Name is still null")
}
// Koltin's scope function
var name:String? = "Kotlin"

name?.let{nonNullableName->
// Kotlin is smart enough to infer the type of name here as String 😎
print("Name is: $nonNullableName")
}

Chaining

  struct Language{
let name:String
}

// Optional object
var swift:Language? = Language(name: "Swift")

// Note here object is nullable not its property
print("Language name:\(swift?.name ?? "Swift")")
data class Language(val name: String)

var kotlin:Language? = Language("Kotlin")

print("Name is: ${kotlin?.name}")

guard let

func getFormattedName(name: String?) -> String{

guard let name = name else {
// fallback name
return "No name found"
}

// only executes if name is not nil
return "Nmae is: \(name)"
}

// call the func and print its result
print("Formatted name: \(getFormattedName(name: nil))")

Check the full code for Swift

Swift optionals

Check the full code for kotlin

Kotlin Nullability

😊😊 👏👏👏👏 HAPPY CODING 👏👏👏👏 😊😊

Nav Singh
Nav Singh

Written by Nav Singh

Google Developer Expert for Android | Mobile Software Engineer at Manulife | Organizer at GDG Montreal

No responses yet