The curious case of Optionals — #1 Emptiness

Swift introduced optionals so that a variable could also have a state of emptiness?


Optionals & emptiness have a lot in common but before we discuss their relationship, let’s try to understand a few basic things:

  • What defines emptiness
// these could be api values from your serverlet num1: Int? = Int("123") // 123
let num2: Int? = Int("abc") // nil
  • num2 is nil; you can use it to show some placeholder or some form of empty state UI
  • empty-value — you can assign a value for a type which could represent the state of emptiness. This approach is very project specific, totally dependent on the business logic & can’t be generalised! Lets take few types and their proposed empty values..
let name: String = ""
let likes: Int = 0
let height: Double = 0.0
let starred: Bool = false
let feedList: [Feed] = []

Lets conclude the relationship between optional & emptiness!

let name1: String? = ""
if let name = name1, !name.isEmpty { ... }
let name2: String = ""
if !name2.isEmpty { ... }
let list: [String]? = ["a", "b", "c"]
if let list = list, !list.isEmpty { ... }
let list: [String] = ["a", "b", "c"]
if !list.isEmpty { ... }
  • If your business logic is such that having a nil value is handled in a different way than having empty Strings/Arrays or other default values (which is normal as well, business logic is weird) then you have to add those extra checks to make sure its handled properly 👍

Coming soon — The curious case of Optionals — #2 Overuse

iOS Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store